0%

Python 数据容器之Dict字典

这里介绍Python数据容器的Dict字典

abstract.png

创建字典

定义:使用花括号{}定义字典,用:冒号定义键值对,用逗号分隔键值对

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# 使用花括号{}定义字典,用:冒号定义键值对,用逗号分隔键值对
person1 = {"first_name": "Aaron", 123: "Zhu"}
person2 = {}
# 使用dict函数创建空字典
person3 = dict()
print("person1:",person1)
print("person2:",person2)
print("person3:",person3)

# dict函数:使用键值对创建字典
dict11 = dict(tom=23, tony=18)
print("dict 1 : ", dict11)

# dict函数:使用键-值对序列 创建字典
person_info_list = [ ["name","Luca"], ["sex","man"] ]
dict2 = dict(person_info_list)
print("dict 2 : ", dict2)

# 创建包含指定键的字典。其中相应的值为None
price_dict_1 = dict.fromkeys(["price1","price2", "price3"])
print("price dict 1 : ", price_dict_1)

# 创建包含指定键的字典。其中相应的值为指定值
price_dict_2 = dict.fromkeys(["price1","price2", "price3"], 9966.123)
print("price dict 2 : ", price_dict_2)

figure 1.png

字典基本操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
print("--------------- 字典基本操作 ---------------")
person1 = {"first_name": "Aaron", "last_name": "Zhu", "age":18}

# len函数:计算字典中键值对的数量
print("person key-value nums:", len(person1))

# 使用键访问其在字典中对应的值
print("person1 -> last_name :", person1["last_name"])
print("person1 -> age :", person1["age"])
try:
# 访问字典中不存在的Key会报错
print("person1 phone number: ", person1["phone_number"])
except Exception as e:
print("Happen Exception: ", e)

# get方法: 访问字典中不存在的key时不会报错。默认会返回None。其中,默认值支持自定义
print("person1 first name: ", person1.get("first_name"))
print("person1 first name: ", person1.get("first_name","Tony"))
print("person1 phone number: ", person1.get("phone_number"))
print("person1 phone number: ", person1.get("phone_number", "110"))

# in/not in: 成员资格判断。判断指定字典中是否存在指定Key
print("key age in person1 : ", "age" in person1)
print("key Aaron in person1 : ", "Aaron" in person1)
print("key my_age not in person1 : ", "my_age" not in person1)

# 对字典中不存在的key进行赋值操作,本质上相当于新增键值对
person1["last_name"] = "Wang"
# 对字典中已存在的key进行赋值操作,本质上相当于修改键值对
person1["sex"] = "man"
print("after modify person1:",person1)

# del语句: 删除字典的指定键值对
del person1["first_name"]
print("after del first name, person1:",person1)
# pop方法:删除字典的指定键值对,同时返回被删除键对应的值
my_age = person1.pop("age")
print("my_age:",my_age)
print("after del age, person1:",person1)

# popitem方法:随机删除字典中的一个键值对并返回
kv_tuple = person1.popitem()
print("after del random key-value, person1:",person1)
print("kv tuple:", kv_tuple)

# clear方法: 清空字典
person1.clear()
print("after clear person1:",person1)

figure 2.png

其他方法

setdefault方法

setdefault(key, default_value) 方法:

  • 如果字典中包含有给定key,则返回字典中该key对应的值;
  • 如果字典中不包含给定key,则会向字典中添加key并将值设为default_value,同时返回default_value
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
word_index = {"is":[42,23,17], "are":[31,83], "where":[2]}

is_index = word_index.setdefault("is",[])
print("word index : ", word_index)
print("is_index : ", is_index)
# 输出:
# word index : {'is': [42, 23, 17], 'are': [31, 83], 'where': [2]}
# is_index : [42, 23, 17]

she_index = word_index.setdefault("she",[])
print("word index : ", word_index)
print("she_index : ", she_index)
# 输出:
# word index : {'is': [42, 23, 17], 'are': [31, 83], 'where': [2], 'she': []}
# she_index : []

字典视图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
person = {"first_name": "Aaron", "last_name": "Zhu", "age":18}

print("--------------- 字典: 键视图 ---------------")
# keys方法:获取字典的键视图
keys = person.keys()
print("keys :", keys)
# 遍历键视图
for key in keys:
print(key," --->>> ", person[key])

print("--------------- 字典: 值视图 ---------------")
# values方法:获取字典的值视图
values = person.values()
print("values :", values)
# 遍历值视图
for value in values:
print("value:", value)

print("--------------- 字典: 键值对视图 ---------------")
# items方法:获取字典的键值对视图
items = person.items()
print("items: ", items)
# 遍历键值对视图

for kv in items:
print("kv : " , kv)

# 由上可知,items()方法以元组的方式返回键值对
# 故这里可通过序列解包的方式,将键、值分别赋值key、value变量
for key, value in items:
print("key: ", key, " value:", value)

figure 3.png

其他字典

默认字典defaultdict

对于collections模块的默认字典defaultdict而言,需要向构造方法提供 一个可调用的对象 作为默认值工厂,用于创造默认值。需要注意的是,默认值工厂只会在 getitem()方法 里被调用,在其他的方法里完全不会发挥作用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import collections

people_info = collections.defaultdict( lambda : 14 )
people_info["Tony"] = 37
people_info["Aaron"] = 18

print(f"people info: {people_info}")
print(f"people info: Aaron -->> {people_info['Aaron']}")

# 通过dict[key]表达式访问时,会调用__getitem__()方法
# 此时,对于字典中不存在的key,defaultdict会调用 可调用对象来创造默认值value
# 然后,向字典中添加key并将值设为默认值value,同时dict[key]表达式返回value
print(f"people info: Lucy -->> {people_info['Lucy']}")


# 通过dict.get(key)表达式访问时,并不会调用__getitem__()方法
# 故,不仅不会向字典中添加key-value对,同时会返回None
print(f"people info: Davlid -->> {people_info.get('Davlid')}")
print(f"people info: {people_info}")

# 输出:
# people info: defaultdict(<function <lambda> at 0x1009544a0>, {'Tony': 37, 'Aaron': 18})
# people info: Aaron -->> 18
# people info: Lucy -->> 14
# people info: Davlid -->> None
# people info: defaultdict(<function <lambda> at 0x1009544a0>, {'Tony': 37, 'Aaron': 18, 'Lucy': 14})

有序字典OrderedDict

普通字典是无序的。但对于collections模块的默认字典OrderedDict而言,其可以记住键值对添加的顺序。使得遍历字典键值对的顺序为添加的顺序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import collections

people_info = collections.OrderedDict()
people_info["Tony"] = 22
people_info["Amy"] = 71
people_info["Lucy"] = 56
people_info["Bob"] = 43

print(f"dict: {people_info}")

for k,v in people_info.items():
print(f"entry: {k} --->>> {v}")

# 输出:
# dict: OrderedDict([('Tony', 22), ('Amy', 71), ('Lucy', 56), ('Bob', 43)])
# entry: Tony --->>> 22
# entry: Amy --->>> 71
# entry: Lucy --->>> 56
# entry: Bob --->>> 43

ChainMap

collections模块的ChainMap,可用于合并多个字典的视图。进行统一的操作,避免遍历多个字典。查询时,会按构造时传入字典的顺序依次进行查询,直到找到第一个时停止

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import collections

people1 = {"Aaron":17, "Bob":22}
people2 = {"Tony":45, "Bob":87}
people = collections.ChainMap(people1, people2)

print(f"people chain map: {people}")
print(f"Aaron -- >> {people['Aaron']}")
# 对于多个字典的重复key,传入字典的顺序依次进行查询,直到找到第一个时停止
print(f"Bob -- >> {people['Bob']}")
print(f"Tony -- >> {people['Tony']}")

# 输出:
# people chain map: ChainMap({'Aaron': 17, 'Bob': 22}, {'Tony': 45, 'Bob': 87})
# Aaron -- >> 17
# Bob -- >> 22
# Tony -- >> 45

参考文献

  1. Python编程·第3版:从入门到实践 Eric Matthes著
  2. Python基础教程·第3版 Magnus Lie Hetland著
  3. 流畅的Python·第1版 Luciano Ramalho著
请我喝杯咖啡捏~
  • 本文作者: Aaron Zhu
  • 本文链接: https://xyzghio.xyz/DictOfPy/
  • 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-ND 许可协议。转载请注明出处!

欢迎关注我的微信公众号:青灯抽丝