多语言展示
当前在线:953今日阅读:26今日分享:39

Python字典操作实例

Python字典操作实例
工具/原料
1

Python

2

windows电脑

方法/步骤
1

打开Python开发工具IDLE,新建‘dict.py’文件,编写代码如下:dic = {1:'first',2:'second',3:'third'}print (dic)print (type(dic.items()))print (dic.items())print (type(dic.keys()))print (dic.keys())print (type(dic.values()))print (list(dic.values()))dic是一个简单的字典,字典与json区别在于json的key必须是字符串,而字典可以是数字,字符串等。

2

F5运行程序,查看打印出的结果dic.items()可以理解将字典转换为列表,dic.keys()字典key转换列表dic.values()字典value转列表{1: 'first', 2: 'second', 3: 'third'}dict_items([(1, 'first'), (2, 'second'), (3, 'third')])dict_keys([1, 2, 3])['first', 'second', 'third']

4

F5运行程序,打印出各自的结果。[(0, 'zero'), (1, 'first'), (2, 'second'), (3, 'third')]{1: 'first', 2: 'second', 3: 'third', 0: 'zero', 4: 'forth'}{1: 'first', 2: 'second', 3: 'third', 0: 'changezero', 4: 'forth'}

5

下面尝试将字符串‘W:1|S:2|X:3’转为字典形式{'W':'1' ,'S':'2', 'X':'3'}代码如下:stro = 'W:1|S:2|X:3'dic = {}for items in stro.split('|'):    key,value = items.split(':')    dic[key]=valueprint (dic)

6

F5运行程序,字符串转换打印出合理的字典了{'W': '1', 'S': '2', 'X': '3'}

推荐信息