字典
字典一种key - value 的数据类型
语法:
info={ ‘01‘:‘Tom‘, ‘02‘:‘Jim‘, ‘03‘:‘Lucy‘, ‘04‘:‘Lily‘ }
字典的特性:
- dict是无序的
- key必须是唯一的,所以自动去重
增加:
In [20]: info[‘05‘]=‘Hans‘ In [21]: print(info) {‘02‘: ‘Jim‘, ‘03‘: ‘Lucy‘, ‘01‘: ‘Tom‘, ‘04‘: ‘Lily‘, ‘05‘: ‘Hans‘}
修改:
In [22]: info[‘03‘]=‘LiGang‘ In [23]: print(info) {‘02‘: ‘Jim‘, ‘03‘: ‘LiGang‘, ‘01‘: ‘Tom‘, ‘04‘: ‘Lily‘, ‘05‘: ‘Hans‘}
删除:
删除有两种方法:
dict.pop(key) #第一种方法
In [24]: info.pop(‘01‘) Out[24]: ‘Tom‘ In [25]: print(info) {‘02‘: ‘Jim‘, ‘03‘: ‘LiGang‘, ‘04‘: ‘Lily‘, ‘05‘: ‘Hans‘}
del dict[key] #第二种方法
In [26]: del info[‘05‘] In [27]: print(info) {‘02‘: ‘Jim‘, ‘03‘: ‘LiGang‘, ‘04‘: ‘Lily‘}
还有一种是随机删除
dict.popitem() #随机删除字典里的key和value
In [29]: info.popitem() Out[29]: (‘03‘, ‘LiGang‘) In [30]: info.popitem() Out[30]: (‘04‘, ‘Lily‘) In [31]: info.popitem() --------------------------------------------------------------------------- KeyError Traceback (most recent call last) <ipython-input-31-203673e70575> in <module>() ----> 1 info.popitem() KeyError: ‘popitem(): dictionary is empty‘ In [32]: print(info) {}
查找:
In [35]: info Out[35]: {‘01‘: ‘Tom‘, ‘02‘: ‘Jim‘, ‘03‘: ‘Lucy‘, ‘04‘: ‘Lily‘} In [34]: ‘01‘ in info #标准用法 Out[34]: True
In [36]: info.get(‘01‘) #获取 Out[36]: ‘Tom‘
多级字典嵌套及操作:
时间: 2024-10-19 18:21:11