字典(dict)
定义字典、访问修改字典、添加删除键值对、get方法、遍历字典、视图对象
定义字典
>>> a = {}
>>> user1 = {'name':'小鸟游星野','age':14}
访问修改字典
>>> user1 = {'name':'小鸟游星野','age':14}
>>> user1['name']
'小鸟游星野'
>>> user1['age'] = 13
>>> user1['age']
13
添加删除键值对
>>> user1 = {'name':'小鸟游星野','age':14}
>>> user1['color'] = 'pink'
>>> user1
{'name': '小鸟游星野', 'age': 14, 'color': 'pink'}
>>> del user1['color']
>>> user1
{'name': '小鸟游星野', 'age': 14}
get方法
当你用索引查询一个键但恰好没有这个键的时候,这时候程序就会报错。如果想不报错,那你就可以考虑get方法。
>>> user1
{'name': '小鸟游星野', 'age': 14}
>>> user1['color']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'color'
>>> user1.get('color','没有color')
'没有color'
遍历字典
遍历键值对
>>> user1
{'name': '小鸟游星野', 'age': 17, 'height': 145, 'birthday': '0102'}
>>> for key,value in user1.items():
... print(f"{key}:{value}")
...
name:小鸟游星野
age:17
height:145
birthday:0102
遍历键
>>> user1
{'name': '小鸟游星野', 'age': 17, 'height': 145, 'birthday': '0102'}
>>> for key in user1.keys():
... print(f"{key}")
...
name
age
height
birthday
>>> for key in user1:
... print(f"{key}")
...
name
age
height
birthday
遍历值
>>> user1
{'name': '小鸟游星野', 'age': 17, 'height': 145, 'birthday': '0102'}
>>> for value in user1.values():
... print(value)
...
小鸟游星野
17
145
0102
视图对象
py3直接使用字典的keys、values、items方法 返回的是 视图对象,而不是列表
py2才是列表
但是视图对象可以转换成列表
支持sorted函数,不支持sort方法
>>> user1
{'name': '小鸟游星野', 'age': 17, 'height': 145, 'birthday': '0102'}
>>> user1.keys()
dict_keys(['name', 'age', 'height', 'birthday'])
>>> list(user1.keys())
['name', 'age', 'height', 'birthday']
>>> sorted(user1.keys())
['age', 'birthday', 'height', 'name']
>>> print(user1.keys().sort())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'dict_keys' object has no attribute 'sort'