Python Mapping Types (映射类型) dict

Python Mapping Types {映射类型} dict

Built-in Types
https://docs.python.org/3/library/stdtypes.html

内置类型
https://docs.python.org/zh-cn/3/library/stdtypes.html

A mapping object maps hashable values to arbitrary objects. Mappings are mutable objects. There is currently only one standard mapping type, the dictionary.
mapping 对象会将 hashable 值映射到任意对象。映射属于可变对象。目前仅有一种标准映射类型字典。

A dictionary’s keys are almost arbitrary values. Values that are not hashable, that is, values containing lists, dictionaries or other mutable types (that are compared by value rather than by object identity) may not be used as keys. Numeric types used for keys obey the normal rules for numeric comparison: if two numbers compare equal (such as 1 and 1.0) then they can be used interchangeably to index the same dictionary entry. (Note however, that since computers store floating-point numbers as approximations it is usually unwise to use them as dictionary keys.)
字典的键几乎可以是任何值。非 hashable 的值不可用作键,即包含列表、字典或其他可变类型的值 (此类对象基于值而非对象标识进行比较)。数字类型用作键时遵循数字比较的一般规则:如果两个数值相等 (例如 1 和 1.0) 则两者可以被用来索引同一字典条目。(但是请注意,由于计算机对于浮点数存储的只是近似值,因此将其用作字典键是不明智的。)

Dictionaries can be created by placing a comma-separated list of key: value pairs within braces, for example: {'jack': 4098, 'sjoerd': 4127} or {4098: 'jack', 4127: 'sjoerd'}, or by the dict constructor.
字典可以通过将以逗号分隔的 键: 值 对列表包含于花括号之内来创建,例如: {'jack': 4098, 'sjoerd': 4127} or {4098: 'jack', 4127: 'sjoerd'},也可以通过 dict 构造器来创建。

class dict(**kwarg)
class dict(mapping, **kwarg)
class dict(iterable, **kwarg)

Return a new dictionary initialized from an optional positional argument and a possibly empty set of keyword arguments.
返回一个新的字典,基于可选的位置参数和可能为空的关键字参数集来初始化。

If no positional argument is given, an empty dictionary is created. If a positional argument is given and it is a mapping object, a dictionary is created with the same key-value pairs as the mapping object. Otherwise, the positional argument must be an iterable object. Each item in the iterable must itself be an iterable with exactly two objects. The first object of each item becomes a key in the new dictionary, and the second object the corresponding value. If a key occurs more than once, the last value for that key becomes the corresponding value in the new dictionary.
如果没有给出位置参数,将创建一个空字典。如果给出一个位置参数并且其属于映射对象,将创建一个具有与映射对象相同键值对的字典。否则的话,位置参数必须为一个 iterable 对象。该可迭代对象中的每一项本身必须为一个刚好包含两个元素的可迭代对象。每一项中的第一个对象将成为新字典的一个键,第二个对象将成为其对应的值。如果一个键出现一次以上,该键的最后一个值将成为其在新字典中对应的值。

If keyword arguments are given, the keyword arguments and their values are added to the dictionary created from the positional argument. If a key being added is already present, the value from the keyword argument replaces the value from the positional argument.
如果给出了关键字参数,则关键字参数及其值会被加入到基于位置参数创建的字典。如果要加入的键已存在,来自关键字参数的值将替代来自位置参数的值。

To illustrate, the following examples all return a dictionary equal to {"one": 1, "two": 2, "three": 3}.
作为演示,以下示例返回的字典均等于 {"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})
>>> a == b == c == d == e
True

Providing keyword arguments as in the first example only works for keys that are valid Python identifiers. Otherwise, any valid keys can be used.
像第一个例子那样提供关键字参数的方式只能使用有效的 Python 标识符作为键。其他方式则可使用任何有效的键。

These are the operations that dictionaries support (and therefore, custom mapping types should support too):
这些是字典所支持的操作 (因而自定义的映射类型也应当支持):

len(d)
Return the number of items in the dictionary d.
返回字典 d 中的项数。

d[key]
Return the item of d with key key. Raises a KeyError if key is not in the map.
返回 d 中以 key 为键的项。如果映射中不存在 key 则会引发 KeyError

If a subclass of dict defines a method __missing__() and key is not present, the d[key] operation calls that method with the key key as argument. The d[key] operation then returns or raises whatever is returned or raised by the __missing__(key) call. No other operations or methods invoke __missing__(). If __missing__() is not defined, KeyError is raised. __missing__() must be a method; it cannot be an instance variable:
如果字典的子类定义了方法 __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

The example above shows part of the implementation of collections.Counter. A different __missing__ method is used by collections.defaultdict.
上面的例子显示了 collections.Counter 实现的部分代码。还有另一个不同的 __missing__ 方法是由 collections.defaultdict 所使用的。

d[key] = value
Set d[key] to value.
d[key] 设为 value

del d[key]
Remove d[key] from d. Raises a KeyError if key is not in the map.
d[key]d 中移除。如果映射中不存在 key 则会引发 KeyError

key in d
Return True if d has a key key, else False.
如果 d 中存在键 key 则返回 True,否则返回 False

key not in d
Equivalent to not key in d.
等价于 not key in d

iter(d)
Return an iterator over the keys of the dictionary. This is a shortcut for iter(d.keys()).
返回以字典的键为元素的迭代器。这是 iter(d.keys()) 的快捷方式。

clear()
Remove all items from the dictionary.
移除字典中的所有元素。

copy()
Return a shallow copy of the dictionary.
返回原字典的浅拷贝。

classmethod fromkeys(iterable[, value])
Create a new dictionary with keys from iterable and values set to value.
使用来自 iterable 的键创建一个新字典,并将键值设为 value。

fromkeys() is a class method that returns a new dictionary. value defaults to None.

get(key[, default])
Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.
如果 key 存在于字典中则返回 key 的值,否则返回 default。如果 default 未给出则默认为 None,因而此方法绝不会引发 KeyError

dict.get(key, default=None)
key - 字典中要查找的键。
default - 如果指定键的值不存在时,返回该默认值。
返回指定键的值,如果指定键的值不存在时,返回该默认值 None
针对字典里面嵌套字典,注意 get() 的用法。

(base) yongqiang@yongqiang:~$ python
Python 3.7.6 (default, Jan  8 2020, 19:59:22)
[GCC 7.3.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> dicta = {"cheng": 1, "yong": 2, "qiang": {"first": 9, "second": 6}}
>>> dicta
{'cheng': 1, 'yong': 2, 'qiang': {'first': 9, 'second': 6}}
>>>
>>> dicta.get("cheng")
1
>>>
>>> dicta.get("jing")
>>> dicta.get("jing", 3)
3
>>>
>>> dicta
{'cheng': 1, 'yong': 2, 'qiang': {'first': 9, 'second': 6}}
>>>
>>> dicta.get("qiang")
{'first': 9, 'second': 6}
>>>
>>> dicta.get("qiang").get("second")
6
>>>
>>> exit()
(base) yongqiang@yongqiang:~$

items()
Return a new view of the dictionary’s items ((key, value) pairs). See the documentation of view objects.
返回由字典项 ((键, 值) 对) 组成的一个新视图。参见 视图对象文档。

keys()
Return a new view of the dictionary’s keys. See the documentation of view objects.
返回由字典键组成的一个新视图。参见 视图对象文档。

pop(key[, default])
If key is in the dictionary, remove it and return its value, else return default. If default is not given and key is not in the dictionary, a KeyError is raised.
如果 key 存在于字典中则将其移除并返回其值,否则返回 default。如果 default 未给出且 key 不存在于字典中,则会引发 KeyError。

popitem()
Remove and return a (key, value) pair from the dictionary. Pairs are returned in LIFO order.
从字典中移除并返回一个 (键, 值) 对。键值对会按 LIFO 的顺序被返回。

popitem() is useful to destructively iterate over a dictionary, as often used in set algorithms. If the dictionary is empty, calling popitem() raises a KeyError.
popitem() 适用于对字典进行消耗性的迭代,这在集合算法中经常被使用。如果字典为空,调用 popitem() 将引发 KeyError。

setdefault(key[, default])
If key is in the dictionary, return its value. If not, insert key with a value of default and return default. default defaults to None.
如果字典存在键 key,返回它的值。如果不存在,插入值为 default 的键 key,并返回 defaultdefault 默认为 None

dict.setdefault(key, default=None)
key - 查找的键值。
default - 键不存在时,设置的默认键值。

如果键不存在于字典中,将会添加键并将值设为默认值。如果字典中包含有给定键,则返回该键对应的值,否则返回为该键设置的值。

(base) yongqiang@yongqiang:~$ python
Python 3.7.6 (default, Jan  8 2020, 19:59:22)
[GCC 7.3.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> dicta = {"cheng": 1, "yong": 2}
>>> dicta
{'cheng': 1, 'yong': 2}
>>>
>>> dicta.setdefault("cheng", 6)
1
>>> dicta
{'cheng': 1, 'yong': 2}
>>>
>>> dicta.setdefault("qiang", 9)
9
>>> dicta
{'cheng': 1, 'yong': 2, 'qiang': 9}
>>>
>>> exit()
(base) yongqiang@yongqiang:~$

update([other])
Update the dictionary with the key/value pairs from other, overwriting existing keys. Return None.
使用来自 other 的键/值对更新字典,覆盖原有的键。返回 None

update() accepts either another dictionary object or an iterable of key/value pairs (as tuples or other iterables of length two). If keyword arguments are specified, the dictionary is then updated with those key/value pairs: d.update(red=1, blue=2).
update() 接受另一个字典对象,或者一个包含键/值对 (以长度为二的元组或其他可迭代对象表示) 的可迭代对象。如果给出了关键字参数,则会以其所指定的键/值对更新字典: d.update(red=1, blue=2)

在执行 update() 方法时,如果被更新的字典中己包含对应的键值对,那么原 value 会被覆盖。如果被更新的字典中不包含对应的键值对,则该键值对被添加进去。

(base) yongqiang@yongqiang:~$ python
Python 3.7.6 (default, Jan  8 2020, 19:59:22)
[GCC 7.3.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> dicta = {"cheng": 1, "yong": 2}
>>> dicta
{'cheng': 1, 'yong': 2}
>>>
>>> dictb = {"qiang": 3}
>>> dictb
{'qiang': 3}
>>>
>>> dicta.update(dictb)
>>>
>>> dicta
{'cheng': 1, 'yong': 2, 'qiang': 3}
>>>
>>> exit()
(base) yongqiang@yongqiang:~$
(base) yongqiang@yongqiang:~$ python
Python 3.7.6 (default, Jan  8 2020, 19:59:22)
[GCC 7.3.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> dicta = {"cheng": 1, "yong": 2}
>>> dicta
{'cheng': 1, 'yong': 2}
>>>
>>> dictb = {"yong": 9, "qiang": 3}
>>> dictb
{'yong': 9, 'qiang': 3}
>>>
>>> dicta.update(dictb)
>>> dicta
{'cheng': 1, 'yong': 9, 'qiang': 3}
>>>
>>> exit()
(base) yongqiang@yongqiang:~$

values()
Return a new view of the dictionary’s values. See the documentation of view objects.
返回由字典值组成的一个新视图。参见 视图对象文档。

Dictionaries compare equal if and only if they have the same (key, value) pairs. Order comparisons (‘<’, ‘<=’, ‘>=’, ‘>’) raise TypeError.
两个字典的比较当且仅当具有相同的 (键, 值) 对时才会相等。顺序比较 (‘<’, ‘<=’, ‘>=’, ‘>’) 会引发 TypeError

Dictionaries preserve insertion order. Note that updating a key does not affect the order. Keys added after deletion are inserted at the end.
字典会保留插入时的顺序。请注意对键的更新不会影响顺序。删除并再次添加的键将被插入到末尾。

>>> 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}

dict 是 Python 中唯一的映射类型 (Mapping Types)。

删除 / 移除 dict 中的所有元素的函数是 clear()

返回包含 dict 中所有键的列表的函数是 keys()

返回包含 dict 中所有值的列表的函数是 values()

返回包含 dict 中所有项 ((键, 值) 对) 的列表的函数是 items()

可以将一个字典的内容添加到另外一个字典中的函数是 update() / update([other])

判断一个键是否在字典中存在的函数是 key in d

References

[1] Yongqiang Cheng, https://yongqiang.blog.csdn.net/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Yongqiang Cheng

梦想不是浮躁,而是沉淀和积累。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值