1 # 字典是一种无序的集合,通常用于描述某个对象的信息
2 user = {
3 "name": "wyc",
4 "age": 22,
5 "gender": "male"
6 }
7
8 # 取值
9 print(user["name"])
10
11 # 根据key来取值,不存在则返回设置的值
12 print(user.get("name", 0))
13
14 # saveorupdate
15 user["name"] = "yeye"
16 user["xx"] = "xx"
17
18
19 # 删除
20 user.pop("name")
21
22 # 合并字典,相同的key-value会被覆盖
23 user.update({"name": "xxx"})
24
25
26 # 清除
27 # user.clear()
28
29 print(user)
30
31 # 统计长度
32 print(len(user))
33
34
35 # 遍历
36 for key in user:
37 print("%s -- %s" % (key, user[key]))
38
39
40 for tuples in user.items():
41 print("%s ---- %s" % (tuples[0], tuples[1]))
42
43 # dict推导式
44 # v,k互换
45 my_dict = {v: k for k, v in user.items()}
46 print(my_dict)