用法:
class dict(**kwargs)class dict(mapping, **kwargs)class dict(iterable, **kwargs)返回一个从可选位置参数和一组可能为空的关键字参数初始化的新字典。
可以通过多种方式创建字典:
- 在大括号内使用逗号分隔的
key: value对列表:{'jack': 4098, 'sjoerd': 4127}或{4098: 'jack', 4127: 'sjoerd'} - 使用字典理解:
{},{x: x ** 2 for x in range(10)} - 使用类型构造函数:
dict(),dict([('foo', 100), ('bar', 200)]),dict(foo=100, bar=200)
如果没有给出位置参数,则创建一个空字典。如果给定位置参数并且它是映射对象,则使用与映射对象相同的键值对创建字典。否则,位置参数必须是可迭代对象。可迭代对象中的每个项目本身必须是恰好具有两个对象的可迭代对象。每个项目的第一个对象成为新字典中的键,第二个对象成为相应的值。如果一个键出现多次,则该键的最后一个值将成为新字典中的对应值。
如果给出了关键字参数,则将关键字参数及其值添加到从位置参数创建的字典中。如果要添加的键已经存在,则关键字参数的值将替换位置参数的值。
为了说明,以下示例都返回一个等于
{"one": 1, "two": 2, "three": 3}的字典:>>> a = dict(one=1, two=2, three=3) >>> b = {'one': 1, 'two': 2, 'three': 3} >>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3])) >>> d = dict([('two', 2), ('one', 1), ('three', 3)]) >>> e = dict({'three': 3, 'one': 1, 'two': 2}) >>> f = dict({'one': 1, 'three': 3}, two=2) >>> a == b == c == d == e == f True在第一个示例中提供关键字参数仅适用于作为有效 Python 标识符的键。否则,可以使用任何有效的 key 。
这些是字典支持的操作(因此,自定义映射类型也应该支持):
-
list(d) 返回字典
d中使用的所有键的列表。
-
len(d) 返回字典
d中的项目数。
-
d[key] 使用键
key返回d的项目。如果key不在Map中,则引发KeyError。如果 dict 的子类定义了方法
__missing__()并且key不存在,则d[key]操作使用键key作为参数调用该方法。然后d[key]操作返回或引发__missing__(key)调用返回或引发的任何内容。没有其他操作或方法调用__missing__()。如果未定义__missing__(),则会引发KeyError。__missing__()必须是方法;它不能是实例变量:>>> class Counter(dict): ... def __missing__(self, key): ... return 0 >>> c = Counter() >>> c['red'] 0 >>> c['red'] += 1 >>> c['red'] 1上面的示例显示了
collections.Counter的部分实现。collections.defaultdict使用了不同的__missing__方法。
-
d[key] = value 将
d[key]设置为value。
-
del d[key] 从
d中删除d[key]。如果key不在Map中,则引发KeyError。
-
key in d 如果
d有键key,则返回True,否则返回False。
-
key not in d 等效于
not key in d。
-
iter(d) 返回字典键的迭代器。这是
iter(d.keys())的快捷方式。
-
reversed(d) 在字典的键上返回一个反向迭代器。这是
reversed(d.keys())的快捷方式。3.8 版中的新函数。
-
d | other 使用合并的
d和other的键和值创建一个新字典,它们必须都是字典。当d和other共享 key 时,other的值优先。3.9 版中的新函数。
-
d |= other 使用来自
other的键和值更新字典d,这可能是键/值对的映射或迭代。当d和other共享 key 时,other的值优先。3.9 版中的新函数。
字典比较相等当且仅当它们具有相同的
(key, value)对(无论顺序如何)。订单比较('='、'>')引发TypeError。字典保留插入顺序。请注意,更新 key 不会影响顺序。删除后添加的键插入到最后。
>>> d = {"one": 1, "two": 2, "three": 3, "four": 4} >>> d {'one': 1, 'two': 2, 'three': 3, 'four': 4} >>> list(d) ['one', 'two', 'three', 'four'] >>> list(d.values()) [1, 2, 3, 4] >>> d["one"] = 42 >>> d {'one': 42, 'two': 2, 'three': 3, 'four': 4} >>> del d["two"] >>> d["two"] = None >>> d {'one': 42, 'three': 3, 'four': 4, 'two': None}在 3.7 版中更改:字典顺序保证为插入顺序。这种行为是 CPython 3.6 的实现细节。
字典和字典视图是可逆的。
>>> d = {"one": 1, "two": 2, "three": 3, "four": 4} >>> d {'one': 1, 'two': 2, 'three': 3, 'four': 4} >>> list(reversed(d)) ['four', 'three', 'two', 'one'] >>> list(reversed(d.values())) [4, 3, 2, 1] >>> list(reversed(d.items())) [('four', 4), ('three', 3), ('two', 2), ('one', 1)]在 3.8 版中更改:字典现在是可逆的。
- 在大括号内使用逗号分隔的
相关用法
- Python dict()用法及代码示例
- Python dictionary update()用法及代码示例
- Python dictionary values()用法及代码示例
- Python dictionary type()用法及代码示例
- Python dictionary fromkeys()用法及代码示例
- Python dictionary cmp()用法及代码示例
- Python dictionary get()用法及代码示例
- Python dict.values用法及代码示例
- Python dictionary setdefault()用法及代码示例
- Python distributed.protocol.serialize.register_generic用法及代码示例
- Python distributed.Client.gather用法及代码示例
- Python distributed.recreate_tasks.ReplayTaskClient.recreate_task_locally用法及代码示例
- Python distributed.diagnostics.plugin.SchedulerPlugin用法及代码示例
- Python distributed.Client.ncores用法及代码示例
- Python distributed.Client.retire_workers用法及代码示例
- Python distributed.Client.unregister_worker_plugin用法及代码示例
- Python distributed.fire_and_forget用法及代码示例
- Python dir用法及代码示例
- Python distributed.Client.set_metadata用法及代码示例
- Python distributed.Client.scheduler_info用法及代码示例
注:本文由纯净天空筛选整理自python.org大神的英文原创作品 dict。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。
