python 容器字典(Dictionaries)简介。
1、字典容器用于存储(key,value)对,是对哈希表的实现,访问时间复杂度为o(1).
简单用法如下:
d = {'cat': 'cute', 'dog': 'furry'} # Create a new dictionary with some data
print(d['cat']) # Get an entry from a dictionary; prints "cute"
print('cat' in d) # Check if a dictionary has a given key; prints "争欧True"
d['fish'] = 'wet' # Set an entry in a dictionary
print(d['fish']) # Prints "wet"
# print(d['monkey']) # KeyError: 'monkey' not a key of d
print(d.get('monkey', 'N/A')) # Get an element with a default; prints "N/A"
print(d.get('fish', 'N/A')) # Get an element with a default; prints "wet"
del d['fish'] # Remove an element from a dictionary
print(d.get('fish', 'N/A')) # "fish" is no longer a key; prints "N/A"

2、上述代码运行结果:
cute
True
wet
N/A
wet
N/A

3、循环:遍历字典中的key非常简单。
实现如下:
d = {'person': 2, 'cat': 4, 'spider': 8}
for animal in d:
legs = d[animal]
print('A %s has %d legs' % (animal, legs))
# Prints "A person has 2 legs", "A cat has 4 legs", "A spider has 8 legs"

4、结果如下:
A person has 2 legs
A cat has 4 legs
A spider has 8 legs

5、如果你低匠想同时获取字典的key和相应召喝压的value的话,可以使用items方法。
举个例子:
d = {'person': 2, 'cat': 4, 'spider': 8}
for animal, legs in d.items():
print('A %s has %d legs' % (animal, legs))
# Prints "A person has 2 legs", "A cat has 4 legs", "A spider has 8 legs"

6、结果如下:
A person has 2 legs
A cat has 4 legs
A spider has 8 legs

7、可以简单的通过列表构建字典。
举个例子:
nums = [0, 1, 2, 3, 4]
even_num_to_square = {x: x ** 2 for x in nums if x % 2 == 0}
print(even_num_to_square) # Prints "{0: 0, 2: 4, 4: 16}"
结果为:
{0: 0, 2: 4, 4: 16}

