字典的创建
1,可以通过{ } 或者 dict() 函数创建字典对象
>>> a = {"name": "pipi", "age": 17, "job": "teacher"}
b = dict(name="pipi", age=17, job="teacher")
a = dict([("name", "pipi"), ("age", 17), ("job", "teacher")])
2,通过zip()创建字典对象
>>> k=["name", "age", "job"]
>>> q=["pipi", 17, "teacher"]
>>> d=dict(zip(k,q))
>>> d
{'name': 'pipi', 'age': 17, 'job': 'teacher'}
3,通过fromkeys创建值为空的字典
>>> a=dict.fromkeys(["name", "age", "job"])
>>> a
{'name': None, 'age': None, 'job': None}
字典元素的访问
1,通过键获得值,若键不存在,会抛出异常
>>> a = {"name": "pipi", "age": 17, "job": "teacher"}
>>> a["name"]
'pipi'
>>> a["job"]
'teacher'
2,通过get()方法获得值 推荐使用
指定的键不存在时,会返回None。 也可以设定指定键不存在时,默认返回的对象。
>>> a = {"name": "pipi", "age": 17, "job": "teacher"}
>>> a.get("name")
'pipi'
>>> a.get("address")
>>> print(a.get("address"))
None
>>> a.get("address","字典里没有地址")
'字典里没有地址'
3,items()方法列出所有的键值对
>>> a = {"name": "pipi", "age": 17, "job": "teacher"}
>>> a.items()
dict_items([('name', 'pipi'), ('age', 17), ('job', 'teacher')])
4,keys()方法获取所有的键 values()方法获取所有的值
>>> a = {"name": "pipi", "age": 17, "job": "teacher"}
>>> a.keys()
dict_keys(['name', 'age', 'job'])
>>> a.values()
dict_values(['pipi', 17, 'teacher'])
5,检测一个键是否在字典中
>>> a = {"name": "pipi", "age": 17, "job": "teacher"}
>>> "name" in a
True
>>> "address" in a
False
字典元素的添加 修改 删除
1,给字典新增键值对,如果键已经存在,那么会覆盖旧的的键的值。如果键不存在,那么会新增键值对
>>> a = {"name": "pipi", "age": 17, "job": "teacher"}
>>> a["age"] = 20
>>> a
{'name': 'pipi', 'age': 20, 'job': 'teacher'}
>>> a["address"] = "北京"
>>> a
{'name': 'pipi', 'age': 20, 'job': 'teacher', 'address': '北京'}
2,update()方法更新键值对,如果key有重复会直接覆盖
>>> a = {"name": "pipi", "age": 17, "job": "teacher"}
>>> b = {"name": "binbin", "address": "beijing"}
>>> b.update(a)
>>> b
{'name': 'pipi', 'address': 'beijing', 'age': 17, 'job': 'teacher'}
3,del(), clear(), pop() 方法删除字典中的元素 注:pop方法有返回值
>>> a = {"name": "pipi", "age": 17, "job": "teacher"}
>>> del(a["name"])
>>> a
{'age': 17, 'job': 'teacher'}
>>> a = {"name": "pipi", "age": 17, "job": "teacher"}
>>> a.pop("age")
17
>>> a = {"name": "pipi", "age": 17, "job": "teacher"}
>>> a.clear()
>>> a
{}
popitem()方法是随机删除和返回改键值对,一个一个的随机弹出
>>> a = {"name": "pipi", "age": 17, "job": "teacher"}
>>> a.popitem()
('job', 'teacher')
>>> a
{'name': 'pipi', 'age': 17}
>>> a.popitem()
('age', 17)
>>> a
{'name': 'pipi'}
>>> a.popitem()
('name', 'pipi')
>>> a
{}
**
序列解包
**
序列解包可以用于元组,列表,字典
序列解包可以方便的对多个变量赋值
>>> a,b,c=1,5,7
>>> a
1
>>> c
7
>>> e,f,g=(2,7,9)
>>> g
9
>>> e,r,t=[4,8,3]
>>> e
4
序列解包用于字典时,默认是对键进行操作。
items()方法是对键值对操作
values()方法是对值进行操作
>>> a = {"name": "pipi", "age": 17, "job": "teacher"}
>>> e,f,g=a #默认对键进行操作
>>> f
'age'
>>> g
'job'
>>> a = {"name": "pipi", "age": 17, "job": "teacher"}
>>> e,f,g=a.items() #对键值对进行操作
>>> e
('name', 'pipi')
>>> g
('job', 'teacher')
>>> a = {"name": "pipi", "age": 17, "job": "teacher"}
>>> e,f,g=a.values() #对值进行操作
>>> g
'teacher'
>>> e
'pipi'