标签:update item 通用 默认 方式 可变 ble 不可 返回
字典可以用来存储含有描述性信息的数据,可读性比其他类型高,比如{"name":"wu","age":24}
它是以键值对的形式存储数据
d={‘k1‘:111,(1,2,3):222} # d=dict(...) print(d[‘k1‘]) # 111 print(d[(1,2,3)]) # 222 print(type(d)) # <class ‘dict‘> ? d={} # 默认定义出来的是空字典 print(d,type(d)) # {} <class ‘dict‘>
d = dict(x=1, y=2, z=3) print(d, type(d)) # {‘x‘: 1, ‘y‘: 2, ‘z‘: 3} <class ‘dict‘>
info = [ [‘name‘, ‘egon‘], (‘age‘, 18), [‘gender‘, ‘male‘] ] d = {} for k, v in info: # k,v=[‘name‘,‘egon‘], d[k] = v print(d) # {‘name‘: ‘egon‘, ‘age‘: 18, ‘gender‘: ‘male‘} info = [ [‘name‘, ‘egon‘], (‘age‘, 18), [‘gender‘, ‘male‘] ] res=dict(info) # 一行代码搞定上述for循环的工作 print(res) # {‘name‘: ‘egon‘, ‘age‘: 18, ‘gender‘: ‘male‘}
keys=[‘name‘,‘age‘,‘gender‘] # d={} # for k in keys: # d[k]=None # print(d) d={}.fromkeys(keys,None) # 一行代码搞定上述for循环的工作 print(d) ?
转换成字典需要两层容器类型,并且内层存放数据的形式为每个键值对放在同一个容器内
pyinfo = [ [‘name‘, ‘egon‘], (‘age‘, 18), [‘gender‘, ‘male‘] ] res=dict(info) print(res) ? # {‘name‘: ‘egon‘, ‘age‘: 18, ‘gender‘: ‘male‘}
d={‘k1‘:111} ? # 针对赋值操作:如果key存在,则修改 d[‘k1‘]=222 ? # 针对赋值操作:如果key不存在,则创建新值 d[‘k2‘]=3333 ? print(d) # {‘k1‘: 222, ‘k2‘: 3333}
d={‘k1‘:111,‘k2‘:2222,‘k1‘:3333,‘k1‘:4444} print(len(d)) # 4
d={‘k1‘:111,‘k2‘:2222} print(‘k1‘ in d) # True print(111 in d) # 只检测key # False
d={‘k1‘:111,‘k2‘:2222} del d[‘k1‘] print(d)
d={‘k1‘:111,‘k2‘:2222} res=d.pop(‘k2‘) print(d) print(res)
d={‘k1‘:111,‘k2‘:2222} res=d.popitem() print(d) # {‘k1‘: 111} ? print(res) # (‘k2‘, 2222)
d={‘k1‘:111,‘k2‘:2222} ? d.keys() [‘k2‘, ‘k1‘] d.values() [2222, 111] d.items() [(‘k2‘, 2222), (‘k1‘, 111)] dict(d.items()) {‘k2‘: 2222, ‘k1‘: 111}
d={‘k1‘:111,‘k2‘:2222} for k in d.keys(): print(k) # k1 # k2 ? for k in d: print(k) # k1 # k2 ? for v in d.values(): print(v) # 111 # 2222 ? for k,v in d.items(): print(k,v) # k1 111 # k2 2222 ? print(list(d.keys())) # [‘k1‘, ‘k2‘] print(list(d.values())) # [111, 2222] print(list(d.items())) # [(‘k1‘, 111), (‘k2‘, 2222)]
清空字典
d = {‘k1‘: 111} d.clear() print(d) # {}
d={‘k1‘:111} d.update({‘k2‘:222,‘k3‘:333,‘k1‘:111111111111111}) print(d) # {‘k1‘: 111111111111111, ‘k2‘: 222, ‘k3‘: 333}
d={‘k1‘:111} print(d[‘k2‘]) # key不存在则报错 # KeyError: ‘k2‘ ? print(d.get(‘k1‘)) # 111 ? print(d.get(‘k2‘)) # key不存在不报错,返回None
info={} if ‘name‘ in info: ... # 等同于pass else: info[‘name‘]=‘egon‘ print(info) # {‘name‘: ‘egon‘} ? ? ? ? ? info = {} info.setdefault("name", "???") print(info) # {‘name‘: ‘???‘}
?
?
?
?
info = {"name": "wu"} print(info.setdefault("name", "???")) # wu ? print(info) # {‘name‘: ‘wu‘}
info = {} print(info.setdefault("name", "???")) # ??? ? print(info) # {‘name‘: ‘???‘}
标签:update item 通用 默认 方式 可变 ble 不可 返回
原文地址:https://www.cnblogs.com/achai222/p/12464726.html