字典简介
字典是键值存储的示例,也称为 Python 中的映射。它允许你通过引用键来存储和检索元素。由于字典是由密钥引用的,因此它们具有非常快速的查找。由于它们主要用于按键引用项目,因此它们不会被排序。
创造一个字典
字典可以通过多种方式启动:
文字语法
d = {} # empty dict
d = {'key': 'value'} # dict with initial values
Python 3.x >= 3.5
# Also unpacking one or multiple dictionaries with the literal syntax is possible
# makes a shallow copy of otherdict
d = {**otherdict}
# also updates the shallow copy with the contents of the yetanotherdict.
d = {**otherdict, **yetanotherdict}
dict 理解
d = {k:v for k,v in [('key', 'value',)]}
另见: 理解
内置类:dict()
d = dict() # emtpy dict
d = dict(key='value') # explicit keyword arguments
d = dict([('key', 'value')]) # passing in a list of key/value pairs
# make a shallow copy of another dict (only possible if keys are only strings!)
d = dict(**otherdict)
修改字典
要将项添加到字典,只需创建一个带有值的新键:
d['newkey'] = 42
也可以添加 list
和 dictionary
作为值:
d['new_list'] = [1, 2, 3]
d['new_dict'] = {'nested_dict': 1}
要删除项目,请从字典中删除密钥:
del d['newkey']