dict
7 methods可哈希键到任意值的可变映射。
dict.get(key[, default])返回 key 对应的值,键不存在则返回 default。不会抛出异常。
Parameters
| Name | Type | Description |
|---|---|---|
| key | Hashable | 要查找的键。 |
| default | Any | 键不存在时返回的值(默认 None)。 |
Returns
Any
Example
python
d = {'a': 1}
d.get('a') # 1
d.get('b') # None
d.get('b', 0) # 0dict.keys()返回字典键的视图。
Returns
dict_keys
Example
python
d = {'a': 1, 'b': 2}
list(d.keys()) # ['a', 'b']dict.values()返回字典值的视图。
Returns
dict_values
Example
python
d = {'a': 1, 'b': 2}
list(d.values()) # [1, 2]dict.items()返回 (key, value) 键值对的视图。
Returns
dict_items
Example
python
d = {'a': 1, 'b': 2}
list(d.items()) # [('a', 1), ('b', 2)]dict.update([other])用 other 中的键值对更新字典,覆盖已存在的键。
Parameters
| Name | Type | Description |
|---|---|---|
| other | dict | Iterable[(k, v)] | Mapping | 更新来源。 |
Returns
None
Example
python
d = {'a': 1}
d.update({'b': 2, 'a': 10})
# d == {'a': 10, 'b': 2}dict.pop(key[, default])移除 key 并返回其值。键不存在则返回 default(否则抛出 KeyError)。
Parameters
| Name | Type | Description |
|---|---|---|
| key | Hashable | 要移除的键。 |
| default | Any | 键不存在时返回的值。 |
Returns
Any
Example
python
d = {'a': 1, 'b': 2}
d.pop('a') # 1
d.pop('z', 0) # 0dict.setdefault(key[, default])如果 key 在字典中,返回其值。否则插入 key 并设为 default,然后返回 default。
Parameters
| Name | Type | Description |
|---|---|---|
| key | Hashable | 要查找的键。 |
| default | Any | 键不存在时插入的值(默认 None)。 |
Returns
Any
Example
python
d = {'a': 1}
d.setdefault('a', 99) # 1
d.setdefault('b', 2) # 2
# d == {'a': 1, 'b': 2}