day12 Python字典
类:dict
#字典是无序的
1、前戏
info = { "k1": "v1", # 键值对 "k2": "v2" }
2、字典的value可以是任何值
info = { "k1": 18, "k2": True, "k3": [ 11, [], (), 22, 33, { 'kk1': 'vv1', 'kk2': 'vv2', 'kk3': (11,22), } ], "k4": (11,22,33,44) } print(info) 结果: {'k1': 18, 'k2': True, 'k3': [11, [], (), 22, 33, {'kk1': 'vv1', 'kk2': 'vv2', 'kk3': (11, 22)}], 'k4': (11, 22, 33, 44)}
3、 列表、字典不能作为字典的key,key值不能重复。
info ={ #1: 'asdf', "k1": 'asjlkdf', #True: "123",#True不能跟1同时作为key,重复的只显示一个因为1=True #[11,22]: 123 (11,22): 123, #{'k1':'v1'}: 123 } print(info) 结果: {'k1': 'asjlkdf', (11, 22): 123}
4、字典无序
5、索引方式找到指定元素
info = { "k1": 18, 2: True, "k3": [ 11, [], (), 22, 33, { 'kk1': 'vv1', 'kk2': 'vv2', 'kk3': (11,22), } ], "k4": (11,22,33,44) } # v = info['k1'] # print(v) # v = info[2] # print(v) v = info['k3'][5]['kk3'][0] print(v) 结果: 11
6、字典支持del删除
info = { "k1": 18, 2: True, "k3": [ 11, [], (), 22, 33, { 'kk1': 'vv1', 'kk2': 'vv2', 'kk3': (11,22), } ], "k4": (11,22,33,44) } del info['k1'] del info['k3'][5]['kk1'] print(info) 结果: {2: True, 'k3': [11, [], (), 22, 33, {'kk2': 'vv2', 'kk3': (11, 22)}], 'k4': (11, 22, 33, 44)}
7、for循环
info = { "k1": 18, 2: True, "k3": [ 11, [], (), 22, 33, { 'kk1': 'vv1', 'kk2': 'vv2', 'kk3': (11,22), } ], "k4": (11,22,33,44) } #for循环健 for item in info。key: print(item) #结果 k1 2 k3 k4 #for循环值 for item in info.values(): print(item) 结果: 18 True [11, [], (), 22, 33, {'kk1': 'vv1', 'kk2': 'vv2', 'kk3': (11, 22)}] (11, 22, 33, 44) #for循环键值 for k,v in info.items(): print(k,v) 结果: k1 18 2 True k3 [11, [], (), 22, 33, {'kk1': 'vv1', 'kk2': 'vv2', 'kk3': (11, 22)}] k4 (11, 22, 33, 44)
方法:
1、根据序列,创建字典,并指定统一的值
v = dict.fromkeys(["k1",123,"999"],123) print(v) 结果: {'k1': 123, 123: 123, '999': 123}
2、根据Key获取值,key不存在,可以指定默认值None
dic = { "k1":"v1" } v = dic.get('k1',None) #根据Key获取值,key不存在时,可以指定默认值(None) v1 = dic.get("k",None) print(v) print(v1) 结果: v1 None
3、删除并获取值
dic = { "k1": 'v1', "k2": 'v2' } v = dic.pop('k1',None) v1 = dic.pop('k11',None) print(dic,v) print(dic,v1) 结果: {'k2': 'v2'} v1 {'k2': 'v2'} None
4、设置值
dic = { "k1": 'v1', "k2": 'v2' } v = dic.setdefault('k1111','123') print(dic,v) 结果: {'k1': 'v1', 'k2': 'v2', 'k1111': '123'} 123 # 已存在,不设置,获取当前key对应的值 # 不存在,设置,获取当前key对应的值
5、更新
dic = { "k1": 'v1', "k2": 'v2' } dic.update({'k1': '111111','k3': 123}) print(dic) dic.update(k1=123,k3=345,k5="asdf") print(dic) 结果: {'k1': '111111', 'k2': 'v2', 'k3': 123} {'k1': 123, 'k2': 'v2', 'k3': 345, 'k5': 'asdf'}