Python 中的dict是一种数据结构,它把可哈希的_键_与_值_关联起来;在其他编程语言里,它也被称为可动态调整大小的哈希表、哈希映射或关联数组。
字典是 Python 唯一的内置映射类型。
Keys必须可哈希,并且在同一个字典中唯一。
键的类型可以是numbers、str或tuples(由_不可变_的值组成)。
键不能包含lists、dicts或sets这类_可变_的数据结构。
从 Python 3.7 起,dict中键的顺序保证与条目插入的顺序一致。
values可以是任何数据类型或结构。
值还可以_任意_嵌套,因此可以包含列表的列表、子字典,以及其他自定义或复合的数据结构。
给定一个key,字典可以在(平均)常数时间内取出对应的value(与条目数量无关)。
与在list或array中查找某个值(在不知道index位置的情况下)相比,dict占用的内存明显更多,但检索速度非常快。
当条目集合很大,而且需要频繁访问和更新时,字典尤其有用。
创建字典的方法有很多种。
最直接的两种是使用dict()构造函数,或者声明一个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}
可以用方括号([])里的_键_来访问字典中的条目。
如果dict里不存在某个key,就会抛出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'
可以通过给条目的_键_赋值来修改它的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}
可以使用.pop(<key>)方法删除字典条目。
.pop()会移除这一对(key、value),并把其中的value返回出来供你使用。
和.get()一样,.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'
用for item in dict或while item遍历字典时,默认只会迭代_键_。
在同一个循环里,可以用_方括号_访问_值_:
>>> for key in bear:
>>> print((key, bear[key])) #this forms a tuple of (key, value) and prints it.
('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。
在本练习中,你将管理一个库存系统。
库存应按物品名称组织,并记录每种物品的可用数量。
你需要处理向库存中添加物品。每当某个物品在给定的数组中出现一次,该物品在库存中的数量就应增加1。你还需要处理从库存中删除物品:在收到请求时把数量减少1。
最后,你需要实现一个函数,它把给定库存中的所有键值对作为一个由tuples组成的list返回。
实现create_inventory(<input list>)函数,它根据输入的物品数组创建一个“库存”。它应返回一个dict,其中每个物品名称都与对应的数量配对。
>>> create_inventory(["coal", "wood", "wood", "diamond", "diamond", "diamond"])
{"coal":1, "wood":2, "diamond":3}
实现add_items(<inventory dict>, <item list>)函数,它把物品数组添加到传入的库存中:
>>> add_items({"coal":1}, ["wood", "iron", "coal", "wood"])
{"coal":2, "wood":2, "iron":1}
实现decrement_items(<inventory dict>, <items list>)函数,它接收一个物品list。物品在list中每出现一次,你的函数就应把该物品的计数减1:
>>> decrement_items({"coal":3, "diamond":1, "iron":5}, ["diamond", "coal", "iron", "iron"])
{"coal":2, "diamond":0, "iron":3}
库存中物品的计数不应低于 0。如果某个物品在输入list中出现的次数超过了可用的计数,该物品记录的数量应保持在 0。一旦计数降为零,后续的减少计数的请求都应被忽略。
>>> decrement_items({"coal":2, "wood":1, "diamond":2}, ["coal", "coal", "wood", "wood", "diamond"])
{"coal":0, "wood":0, "diamond":1}
实现remove_item(<inventory dict>, <item>)函数,它把某个物品及其计数从库存中彻底删除:
>>> remove_item({"coal":2, "wood":1, "diamond":2}, "coal")
{"wood":1, "diamond":2}
如果在库存中找不到该物品,函数应原样返回原来的库存。
>>> remove_item({"coal":2, "wood":1, "diamond":2}, "gold")
{"coal":2, "wood":1, "diamond":2}
实现list_inventory(<inventory dict>)函数,它接收一个库存,并返回一个由(item, quantity)元组组成的数组。该数组只应包含可用的物品(数量大于零):
>>> list_inventory({"coal":7, "wood":11, "diamond":2, "iron":7, "silver":0})
[('coal', 7), ('diamond', 2), ('iron', 7), ('wood', 11)]