Python 中的字典(dict)是一种数据结构,它把可哈希的_键_关联到_值_,在其他编程语言中也称为可调整大小的哈希表、hashmap 或关联数组。字典是 Python 唯一内置的映射类型。
keys必须可哈希,并且在字典中唯一。
键的类型可以包括number、str或tuple(由_不可变_值组成)。
它们不能包含list、dict或set这类_可变_数据结构。
从 Python 3.7 起,dict的键顺序保证与条目插入的顺序一致。
values可以是任何数据类型或结构。
值还可以_任意_嵌套,因此可以包含数组的数组、子字典,以及其他自定义或复合的数据结构。
给定一个key,字典能在(平均)常数时间内检索出value(与条目的数量无关)。
与在list或array中搜索值(在不知道index位置的情况下)相比,dict占用的内存明显更多,但检索速度非常快。
当条目集合很大,而且需要频繁访问和更新时,字典特别有用。
字典可以通过多种方式创建,包括:
fromkeys() 类方法。**)合并两个字典。|(更新)运算符合并字典。dict添加条目。最直接的两种方法是字典_构造函数_和字典_字面量_。
dict()(dict类的构造函数)可以配合任何由key、value对组成的可迭代对象使用。
也可以用一系列<name>=<value>_实参_来调用:
# Passing a list of key,value tuples.
>>> wombat = dict([('name', 'Wombat'),
... ('speed', 23),
... ('land_animal', True)])
{'name': 'Wombat', 'speed': 23, 'land_animal': True}
# Using key=value arguments.
>>> bear = dict(name="Black Bear",
... speed=40,
... land_animal=True)
{'name': 'Black Bear', 'speed': 40, 'land_animal': True}
关于dict的文档介绍了构造函数用法的更多变体和选项。
字典也可以直接写成_字典字面量_,用大括号({})把key : value对括起来。
{}中的各个条目也可以分行书写:
>>> whale = {"name": "Blue Whale",
"speed": 35,
"land_animal": False}
{'name': 'Blue Whale', 'speed': 35, 'land_animal': False}
>>> wombat = {'name': 'Wombat',
'speed': 23,
'land_animal': True,
'color': 'Brindle'}
>>> wombat
{'name': 'Wombat', 'speed': 23, 'land_animal': True, 'color': 'Brindle'}
字典可以任意嵌套:
animals = {
"Real" : {
"Winged" : {
"Sparrow" : {'name': 'sparrow','speed': 12, 'land_animal': True},
"Kestrel" : {'name': 'kestrel', 'speed': 15, 'land_animal': True}
},
"Legged" : {
"Wombat" : {'name': 'Wombat', 'speed': 23, 'land_animal': True},
"Black Bear": {'name': 'Black Bear', 'speed': 40, 'land_animal': True},
"Polecat" : {'name': 'Polecat', 'speed': 15, 'land_animal': True}
},
"Other" : {
"Whale" : {'name': 'Blue Whale', 'speed': 35, 'land_animal': False},
"Orca" : {'name': 'Orca', 'speed': 45, 'land_animal': False},
"Snake" : {'name': 'Python', 'speed': 25, 'land_animal': True}
}
},
"Imaginary": {
"Winged" : {
"Dragon" : {'name': 'Fire Dragon','speed': 100, 'land_animal': True},
"Phoenix" : {'name': 'Phoenix', 'speed': 1500, 'land_animal': True}
},
"Legged" : {
"Sphinx" : {'name': 'Sphinx','speed': 10, 'land_animal': True},
"Minotaur" : {'name': 'Minotaur', 'speed': 5, 'land_animal': True}
},
"Other" : {}
}
}
dict中的值可以用方括号中的_键_来访问字典里的value。
如果某个键在字典中不存在,就会抛出KeyError:
>>> bear["speed"]
40
>>> bear["color"]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'color'
通过get(<key>, <default value>)方法来访问条目,可以避免KeyError:
>>> bear.get("color", 'not found')
'not found'
要访问嵌套字典中的条目,连续使用方括号即可。 如果某个键不存在,就会抛出通常的 KeyError:
# Using the animals nested dictionary.
>>> animals["Real"]["winged"]["Kestrel"]["speed"]
15
>>> animals["Imaginary"]["winged"]["Kestrel"]["speed"]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'Kestrel'
要避免KeyError,可以使用.get(),但必须_链式_调用.get():
# Using the animals nested dictionary.
# Note the use of parenthesis to enable placing the
# .get() calls on separate lines.
>>> (animals.get("Imaginary", {})
.get("Legged", {})
.get("Sphinx", {})
.get("Color", "I have no idea!"))
'I have no idea!'
可以通过给条目的_键_赋值来修改条目的value:
# Assigning the value "Grizzly Bear" to the name key.
>>> bear["name"] = "Grizzly Bear"
{'name': 'Grizzly Bear', 'speed': 40, 'land_animal': True}
>>> whale["speed"] = 25
{'name': 'Blue Whale', 'speed': 25, 'land_animal': False}
新的key:value对也可以用同样的方式_添加_:
# Adding a new "color" key with a new "tawney" value.
>>> bear["color"] = 'tawney'
{'name': 'Grizzly Bear', 'speed': 40, 'land_animal': True, 'color': 'tawney'}
>>> whale["blowholes"] = 1
{'name': 'Blue Whale', 'speed': 25, 'land_animal': False, 'blowholes': 1}
可以用<dict>.pop(<key>)方法删除字典条目。
<dict>.pop()会移除(key、value)对,并返回value供使用。
和<dict>.get()一样,<dict>.pop(<key>)接受第二个实参(<dict>.pop(<key>, <default value>)),当key不存在时会返回它。
这样可以避免抛出KeyError:
# Using .pop() removes both the key and value, returning the value.
>>> bear.pop("name")
'Grizzly Bear'
# The "name" key is now removed from the dictionary.
# Attempting .pop() a second time will throw a KeyError.
>>> bear.pop("name")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'name'
# Using a default argument with .pop() will
# prevent a KeyError from a missing key.
>>> bear.pop("name", "Unknown")
'Unknown'
也可以用del语句删除一个或多个条目。
如果要删除的条目在字典中找不到,就会抛出KeyError:
>>> wombat = {'name': 'Wombat',
'speed': 23,
'land_animal': True,
'color': 'Brindle',
'talent': 'Singing',
'size': 'small'}
# Remove a single entry from the dictionary.
>>> del wombat["color"]
>>> wombat
{'name': 'Wombat', 'speed': 23, 'land_animal': True, 'talent': 'Singing', 'size': 'small'}
# Remove multiple entries from the dictionary.
>>> del wombat["talent"], wombat["size"]
>>> wombat
{'name': 'Wombat', 'speed': 23, 'land_animal': True}
# Attempting a deletion of a non-existent key raises a KeyError
>>> del wombat["number_of_legs"]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'number_of_legs'
用for item in dict或while item遍历字典时,默认会迭代_键_。
在同一个循环中,可以用_方括号_访问_值_:
>>> for key in bear:
... print((key, bear[key])) # <--This prints a tuple of (key, value).
('name', 'Black Bear')
('speed', 40)
('land_animal', True)
也可以用.items()方法,它返回(key、value)元组:
# dict.items() forms (key, value tuples) that can be
# unpacked and iterated over.
>>> for key, value in whale.items():
... print(key, ":", value)
name : Blue Whale
speed : 25
land_animal : False
blowholes : 1
同样,.keys()会返回keys,.values()会返回values。
想了解 Python 中字典的详细说明,官方文档是非常好的起点,你也可以看看 W3-Schools 教程。
collections模块为 Python 标准的基于集合的数据类型(dict、set、list、tuple)添加了专门的功能。
最实用的基于字典的类有三个:
Counter自动统计条目,并以dict的形式返回,其中条目作为键、计数作为值。OrderedDict有专门用于安排字典条目顺序的方法。defaultdict使用工厂方法,在尝试获取或给字典条目赋值却找不到key时设置默认值。