Python字典使用例子

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值