Python字典基础知识
1.字典数据用花括号包含,以键对值形式表示
2.不同键对值用逗号隔开,键和值用冒号隔开
3.键不能重复,值可以重复;键不能修改,值可以修改
4.值可以是用{}表示的对象
如:
d = {‘key1’:‘12’,‘key2’:‘13’,‘key3’:‘14’}
Python字典基本操作
例1
population = [{'country': 'United Kingdom', 'population': '66181585'}, {'country': 'United States', 'population': '324459463'}]
country_population = {}
for item in world_population:
country_population[item['country']] = int(item['population'])
print(country_population)
输出结果:
{'United Kingdom': 66181585, 'United States': 324459463}
country_population['UK'] = country_population['United Kingdom']
country_population['US'] = country_population['United States']
country_population['Serbia'] = 7057666
print(country_population)
输出结果:
{'United Kingdom': 66181585, 'United States': 324459463, 'UK': 66181585, 'US': 324459463, 'Serbia': 7057666}
例2
history = {'1/1/20':0,'1/2/20':1,'1/3/20':2}
for date in history:
print(date)
输出结果
1/1/20
1/2/20
1/3/20
注:这里遍历的是key.
例3
d = {'number':{'locations':[{"country":'China','history':{'1/1/20':0,'1/2/20':1,'1/3/20':2}},
{"country":'US','history':{'1/1/20':10,'1/2/20':11,'1/3/20':12}},
{"country":'UK', 'history': {'1/1/20': 110, '1/2/20': 111, '1/3/20':112}}]}}
#1
for i,location in enumerate(d['number']['locations']):
print(i, "and", location)
输出结果:
0 and {'country': 'China', 'history': {'1/1/20': 0, '1/2/20': 1, '1/3/20': 2}}
1 and {'country': 'US', 'history': {'1/1/20': 10, '1/2/20': 11, '1/3/20': 12}}
2 and {'country': 'UK', 'history': {'1/1/20': 110, '1/2/20': 111, '1/3/20': 112}}
#2
print(location['country'])
输出结果
China
US
UK
#3
for date in location['history']:
print(date)
number = int(location['history'][date])
print(number)
输出结果:
1/1/20
0
1/2/20
1
1/3/20
2
1/1/20
10
1/2/20
11
1/3/20
12
1/1/20
110
1/2/20
111
1/3/20
112
注1:enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)
组合为一个索引序列,同时列出数据和数据下标,一般用在for 循环当中,数据下标作为一个变量,数据作为第二个变量。
注2:字典d = {‘key’:‘value’},d[‘key’] 指向值value