字典的‘魔法’方法
字典的key是一个可哈希的值,字典的value可以是任何值。
- keys():返回键
1 a = {'a':1,'b':2,'c':3,'d':4} 2 print(a.keys()) 3 #结果:dict_keys(['a', 'b', 'c', 'd'])
- values():返回键对应的值
1 a = {'a':1,'b':2,'c':3,'d':4} 2 print(a.values()) 3 #结果:dict_values([1, 2, 3, 4])
- items():返回键和值
1 a = {'a':1,'b':2,'c':3,'d':4} 2 print(a.items()) 3 #结果:dict_items([('a', 1), ('b', 2), ('c', 3), ('d', 4)])
keys遍历出来
1 a = {'a':1,'b':2,'c':3,'d':4} 2 for i in a.keys(): 3 print(i) 4 #结果: 5 '''a 6 b 7 c 8 d'''
values遍历出来
1 a = {'a':1,'b':2,'c':3,'d':4} 2 for i in a.values(): 3 print(i) 4 #结果: 5 '''1 6 2 7 3 8 4'''
items遍历出来
1 a = {'a':1,'b':2,'c':3,'d':4} 2 for i in a.items(): 3 print(i) 4 #结果: 5 '''('a', 1) 6 ('b', 2) 7 ('c', 3) 8 ('d', 4)'''
- get():根据key获取值,key不存在时,可以指定默认值(None)
1 a = {'a':1,'b':2,'c':3,'d':4} 2 t = a.get('a',465456) 3 print(t) 4 #结果:1
5 t1 = a.get('a') 6 print(t1) 7 #结果:1
8 t2 = a.get('s',45645) 9 print(t2) 10 #结果:45645
11 t3 = a.get('s') 12 print(t3) 13 #结果:None
- pop()
- popitem()
删除并获取键对应的值,可以指定删除键的默认值
1 dic = {"k1": 'v1',"k2": 'v2'} 2 v = dic.pop('k1','sb') 3 print(dic,v) 4 #结果:{'k2': 'v2'} v1
5 v1 = dic.pop('k3','sb') 6 print(dic,v1) 7 #结果:{'k2': 'v2'} sb
8 k3,v3 = dic.popitem() 9 print(dic,k3,v3) 10 #结果:{'k1': 'v1'} k2 v2
- setdefault()
设置字典的值。已存在,不设置,获取当前key对应的值;不存在,设置,获取当前key对应的值。
1 dic = {"k1": 'v1',"k2": 'v2'} 2 v = dic.setdefault('k1111','123') 3 print(dic,v) 4 #结果:{'k1': 'v1', 'k2': 'v2', 'k1111': '123'} 123
5 v1 = dic.setdefault('k1',1231) 6 print(v1) 7 #结果:v1
- update()
1 dic = {"k1": 'v1',"k2": 'v2'} 2 dic.update({'k1': '111111','k3': 123}) 3 print(dic) 4 #结果:{'k1': '111111', 'k2': 'v2', 'k3': 123} 5 dic1 = {"k1": 'v1',"k2": 'v2'} 6 dic1.update(k1=123,k3=345,k5="asdf") 7 print(dic1) 8 #结果:{'k1': 123, 'k2': 'v2', 'k3': 345, 'k5': 'asdf'}
- del
1 dic = {"k1": 'v1',"k2": 'v2'} 2 del dic['k1'] 3 print(dic) 4 #结果:{'k2': 'v2'}