python 字典

437 阅读5分钟

字典是另一种可变容器模型,且可存储任意类型对象。

字典也是 Python提供的一种常用的数据结构,它用于存放具有映射关系的数据。

img

由于字典中的 key 是非常关键的数据,而且程序需要通过 key 来访问 value,因此字典中的 key 不允许重复。

创建 字典

可以使用 {} 语法来创建字典

也可以使用 dict() 函数来创建字典

创建 空字典

empty_dict = {}
print(empty_dict, type(empty_dict))

empty_dict_2 = dict()
print(empty_dict_2, type(empty_dict_2))

# 输出
# {} <class 'dict'>
# {} <class 'dict'>

创建 有数据的 字典

language = {
    'Chinese': '中文',
    'Japanese': '日文',
    'French': '法语'
}
print(language, type(language))

# 输出
# {'Chinese': '中文', 'Japanese': '日文', 'French': '法语'}  <class 'dict'>

在使用 dict() 函数创建字典时,可以传入多个列表或元组参数作为 key-value 对,每个列表或元组将被当成一个 key-value 对,因此这些列表或元组都只能包含两个元素。

data_1 = [('name', '阿怪'), ('age', 18), ('address', '成都')]
dict_1 = dict(data_1)

print(dict_1, type(dict_1))

# 输出
# {'name': '阿怪', 'age': 18, 'address': '成都'} <class 'dict'>

data_2 = [['name', '阿怪'], ['age', 18], ['address', '成都']]
dict_2 = dict(data_2)

print(dict_2, type(dict_2))

# 输出
# {'name': '阿怪', 'age': 18, 'address': '成都'} <class 'dict'>

还可通过为 dict 指定关键字参数创建字典,此时字典的 key 不允许使用表达式

dict_3 = dict(name='阿怪', age=18, address='成都')
print(dict_3, type(dict_3))

# 输出
# {'name': '阿怪', 'age': 18, 'address': '成都'} <class 'dict'>

字典基本用法

字典包含多个 key-value 对,而 key 是字典的关键数据,因此程序对字典的操作都是基于 key 的

  • 通过 key 访问 value 。
  • 通过 key 添加 key-value 对。
  • 通过 key 删除 key-value 对。
  • 通过 key 修改 key-value 对。
  • 通过 key 判断指定 key-value 对是否存在。
  • 通过 key 访问 value 使用的也是方括号语法,就像前面介绍的列表和元组一样,只是此时在方括号中放的是 key,而不是列表或元组中的索引。

通过 key 访问 value

dict_4 = {'name': '阿怪', 'age': 18, 'address': '成都', 'phone': '1518***-****-***'}
print(dict_4['name'], dict_4['phone'])

# 输出
# 阿怪 1518***-****-***

如果要位字典 添加数据, 只需要为不存在的 key 赋值即可

dict_5 = {'name': '阿怪', 'age': 18, 'address': '成都', 'phone': '1518***-****-***'}
dict_5['mail'] = '2537*****.com'

print(dict_5['mail'])
print(dict_5)

# 输出
# 2537*****.com
# {'name': '阿怪', 'age': 18, 'address': '成都', 'phone': '1518***-****-***', 'mail': '2537*****.com'}

字典中 对存在的key-value赋值, 新的 value 会覆盖旧的 value

dict_6 = {'name': '阿怪', 'age': 18, 'address': '成都', 'phone': '1518***-****-***'}
dict_6['phone'] = '1999999999999999'

print(dict_6['phone'])
print(dict_6)

# 输出
# 1999999999999999
# {'name': '阿怪', 'age': 18, 'address': '成都', 'phone': '1999999999999999'}

删除宇典中的 key-value 对, 使用 del语句

dict_7 = {'name': '阿怪', 'age': 18, 'address': '成都', 'phone': '1518***-****-***'}
del dict_7['phone']

print(dict_7)

# 输出
# {'name': '阿怪', 'age': 18, 'address': '成都'}

判断字典 是否包含指定的 key, 使用 in 或者 not in

dict_8 = {'name': '阿怪', 'age': 18, 'address': '成都', 'phone': '1518***-****-***'}

# in 存在为 True 不存在为 False
print('height' in dict_8)

# 输出 False

字典常用方法

**clear()**

clear() 用于清空字典中所有的 key-value 对,对一个字典执行 clear() 方法之后,该字典就会变成一个空字典。

dict_9 = {'name': '阿怪', 'age': 18, 'address': '成都', 'phone': '1518***-****-***'}
dict_9.clear()

print(dict_9)
# 输出
# {}

get()

get() 方法其实就是根据 key 来获取 value,它相当于方括号语法的增强版,当使用方括号语法访问并不存在的 key 时,字典会引发 KeyError 错误;但如果使用 get() 方法访问不存在的 key,该方法会简单地返回 None,不会导致错误。

dict_10 = {'name': '阿怪', 'age': 18, 'address': '成都', 'phone': '1518***-****-***'}

print(dict_10.get('name'))
print(dict_10.get('height'))

# 输出
# 阿怪
# None

pop()

pop() 方法用于获取指定 key 对应的 value,并删除这个 key-value 对。

dict_11 = {'name': '阿怪', 'age': 18, 'address': '成都', 'phone': '1518***-****-***'}
dict_11.pop('age')

print(dict_11)
# 输出
# {'name': '阿怪', 'address': '成都', 'phone': '1518***-****-***'}

popitem()

随机返回并删除字典中的最后一对键和值。

dict_12 = {'name': '阿怪', 'age': 18, 'address': '成都', 'phone': '1518***-****-***'}

print(dict_12.popitem())
print(dict_12)

# 输出
# ('phone', '1518***-****-***')
# {'name': '阿怪', 'age': 18, 'address': '成都'}

update()

update() 方法可使用一个字典所包含的 key-value 对来更新己有的字典。在执行 update() 方法时,如果被更新的字典中己包含对应的 key-value 对,那么原 value 会被覆盖;如果被更新的字典中不包含对应的 key-value 对,则该 key-value 对被添加进去。

dict_13 = {'name': '阿怪', 'age': 18, 'address': '成都', 'phone': '1518***-****-***'}
dict_13.update({'age': 999, 'height': '175cm'})

print(dict_13)
# 输出
# {'name': '阿怪', 'age': 999, 'address': '成都', 'phone': '1518***-****-***', 'height': '175cm'}

字典的遍历方法

遍历key值

dict_14 = {'name': '阿怪', 'age': 18, 'address': '成都', 'phone': '1518***-****-***'}
for key in dict_14:
    print(key, '--->', dict_14[key])

# 输出
# name ---> 阿怪
# age ---> 18
# address ---> 成都
# phone ---> 1518***-****-***

遍历value值

dict_15 = {'name': '阿怪', 'age': 18, 'address': '成都', 'phone': '1518***-****-***'}
for value in dict_15.values():
    print(value)

# 输出
# 阿怪
# 18
# 成都
# 1518***-****-***

遍历字典健值

dict_16 = {'name': '阿怪', 'age': 18, 'address': '成都', 'phone': '1518***-****-***'}
for key, value in dict_16.items():
    print(key, ':', value)

# 输出
# name : 阿怪
# age : 18
# address : 成都
# phone : 1518***-****-***