字典(dict)
定义
In [4]: dt1 = {'name':'ray','age':18,'height':175} In [5]: dt1 Out[5]: {'name': 'ray', 'age': 18, 'height': 175} In [40]: d = {}.fromkeys(('name','tearch'),'ray') ...: In [41]: d Out[41]: {'name': 'ray', 'tearch': 'ray'} In [44]: d = {}.fromkeys(city,code) In [45]: d Out[45]: {'bj': [1, 2, 3], 'sh': [1, 2, 3], 'sz': [1, 2, 3]}
In [6]: dt2 = dict(name='ray',age=18,height=175) In [7]: dt2 Out[7]: {'name': 'ray', 'age': 18, 'height': 175}
获取元素
In [19]: dt1.get('emial','没有这个键') Out[19]: '没有这个键'
In [14]: dt1.get('name') # 不存在返回none Out[14]: 'ray'
In [16]: dt1['name'] # 不存在报错 Out[16]: 'ray'
In [25]: dt1.keys() Out[25]: dict_keys(['name', 'age', 'height']) In [26]: dt1.values() Out[26]: dict_values(['ray', 18, 175]) In [27]: dt1.items() Out[27]: dict_items([('name', 'ray'), ('age', 18), ('height', 175)])
增加元素
In [28]: dt1['weight']=70 In [29]: dt1 Out[29]: {'name': 'ray', 'age': 18, 'height': 175, 'weight': 70} In [43]: dt2.setdefault('weight',70) # 有则显示,无则添加 Out[43]: 70 In [44]: dt2 Out[44]: {'name': 'ray', 'age': 18, 'height': 175, 'weight': 70}
修改元素
In [30]: dt1['height']=170 In [31]: dt1 Out[31]: {'name': 'ray', 'age': 18, 'height': 170, 'weight': 70}
In [32]: other={'hobby':['sports','beautiful girls']} In [33]: dt1.update(other) In [34]: dt1 Out[34]: {'name': 'ray', 'age': 18, 'height': 170, 'weight': 70, 'hobby': ['sports', 'beautiful girls']}
删除
In [36]: dt1.pop('weight','no such key') Out[36]: 70
In [37]: dt1.popitem() Out[37]: ('hobby', ['sports', 'beautiful girls']) In [38]: dt1 Out[38]: {'name': 'ray', 'age': 18, 'height': 170}
In [39]: dt1.clear() In [40]: dt1 Out[40]: {}
循环获取
In [54]: for k,v in dt2.items(): ...: print(k,v)
In [56]: for i in dt2: ...: print(i) ...:
删除
del d_name[key]