字典
字典是另一种可变容器模型,且可存储任意类型对象。
字典的每个键值(key=>value)对用冒号(:)分割,每个对之间用逗号(,)分割,整个字典包括在花括号({})中
语法:
1 goods = { 2 ‘apple‘:4.5, 3 ‘orange‘:2.3, 4 ‘banana‘:3.5 5 }
字典的特性:
- dict是无序的
- key必须是唯一的
1.增加元素
1 >>> goods 2 {‘apple‘: 4.5, ‘banana‘: 3.5, ‘orange‘: 2.3} 3 >>> goods[‘peach‘]=5.0 4 >>> goods 5 {‘apple‘: 4.5, ‘banana‘: 3.5, ‘orange‘: 2.3, ‘peach‘: 5.0}
2.修改
1 >>> goods[‘apple‘]=5.5 # 将苹果的价格改为 5.5 2 >>> goods 3 {‘apple‘: 5.5, ‘banana‘: 3.5, ‘orange‘: 2.3, ‘peach‘: 5.0}
3.删除元素
1 >>> goods 2 {‘apple‘: 5.5, ‘banana‘: 3.5, ‘orange‘: 2.3, ‘peach‘: 5.0} 3 >>> goods.pop(‘peach‘) #删除最后一个,并返回value的值 4 5.0 5 >>> goods 6 {‘apple‘: 5.5, ‘banana‘: 3.5, ‘orange‘: 2.3} 7 8 >>> del goods[‘banana‘] # 指定 key的删除 9 >>> goods 10 {‘apple‘: 5.5, ‘orange‘: 2.3} 11 12 >>> goods 13 {‘apple‘: 5.5, ‘grape‘: 6.0, ‘orange‘: 2.3, ‘watermelon‘: 12.0} 14 >>> goods.popitem() # 随机删除 15 (‘apple‘, 5.5) 16 >>> goods 17 {‘grape‘: 6.0, ‘orange‘: 2.3, ‘watermelon‘: 12.0}
4.查找
1 >>> goods 2 {‘grape‘: 6.0, ‘orange‘: 2.3, ‘watermelon‘: 12.0} 3 >>> ‘grape‘ in goods 4 True 5 >>> goods.get(‘orange‘) # 知道key,获取 value 6 2.3 7 >>> goods[‘watermelon‘] 8 12.0 9 >>> goods[‘apple‘] # 如果一个key不存在,就会报错,get不会,不存在只会返回None 10 Traceback (most recent call last): 11 File "<stdin>", line 1, in <module> 12 KeyError: ‘apple‘
5.多级字典及操作
1 area = {‘浙江‘: 2 { 3 ‘杭州‘:[‘西湖区‘,‘下城区‘,‘萧山区‘], 4 ‘嘉兴‘:[‘南湖区‘,‘秀洲区‘,‘平湖市‘], 5 ‘温州‘:[‘九湾区‘,‘鹿城区‘,‘洞头区‘] 6 }, 7 ‘江苏‘: 8 { 9 ‘南京‘:[‘鼓楼区‘,‘玄武区‘,‘秦淮区‘], 10 ‘苏州‘:[‘姑苏区‘,‘吴中区‘,‘虎丘区‘], 11 ‘常州‘:[‘武进区‘,‘金坛市‘,‘溧阳市‘] 12 } 13 14 15 } 16 17 >>> area[‘浙江‘][‘杭州‘] 18 [‘西湖区‘, ‘下城区‘, ‘萧山区‘] 19 20 21 >>> area[‘浙江‘][‘杭州‘][1] += ‘,很大‘ 22 >>> area[‘浙江‘][‘杭州‘] 23 [‘西湖区‘, ‘下城区,很大‘, ‘萧山区‘]
6.其他用法
1 >>> area.keys() 2 dict_keys([‘浙江‘, ‘江苏‘]) 3 >>> goods.values() 4 dict_values([6.0, 2.3, 12.0]) 5 >>> goods.keys() 6 dict_keys([‘grape‘, ‘orange‘, ‘watermelon‘]) 7 8 {‘grape‘: 6.0, ‘orange‘: 2.3, ‘watermelon‘: 12.0} 9 >>> b = {1:2,3:4,‘grape‘:4.5} 10 >>> goods.update(b) 11 >>> goods 12 {1: 2, 3: 4, ‘grape‘: 4.5, ‘orange‘: 2.3, ‘watermelon‘: 12.0} 13 14 >>> goods.items() 15 dict_items([(1, 2), (3, 4), (‘grape‘, 4.5), (‘orange‘, 2.3), (‘watermelon‘, 12.0)])
7.遍历字典
1 for key in goods: 2 print(key,goods[key]) 3 #或 4 for k,v in goods.items(): 5 print(k,v)
时间: 2024-10-11 07:21:43