dict
7 methodsMutable mapping of hashable keys to arbitrary values.
dict.get(key[, default])Return value for key, or default if key is missing. Does not raise.
Parameters
| Name | Type | Description |
|---|---|---|
| key | Hashable | Key to look up. |
| default | Any | Value returned if key is missing (default None). |
Returns
Any
Example
python
d = {'a': 1}
d.get('a') # 1
d.get('b') # None
d.get('b', 0) # 0dict.keys()Return a view of the dictionary's keys.
Returns
dict_keys
Example
python
d = {'a': 1, 'b': 2}
list(d.keys()) # ['a', 'b']dict.values()Return a view of the dictionary's values.
Returns
dict_values
Example
python
d = {'a': 1, 'b': 2}
list(d.values()) # [1, 2]dict.items()Return a view of (key, value) pairs.
Returns
dict_items
Example
python
d = {'a': 1, 'b': 2}
list(d.items()) # [('a', 1), ('b', 2)]dict.update([other])Update the dict with key/value pairs from other, overwriting existing keys.
Parameters
| Name | Type | Description |
|---|---|---|
| other | dict | Iterable[(k, v)] | Mapping | Source of updates. |
Returns
None
Example
python
d = {'a': 1}
d.update({'b': 2, 'a': 10})
# d == {'a': 10, 'b': 2}dict.pop(key[, default])Remove key and return its value. Returns default if missing (else raises KeyError).
Parameters
| Name | Type | Description |
|---|---|---|
| key | Hashable | Key to remove. |
| default | Any | Returned if key is missing. |
Returns
Any
Example
python
d = {'a': 1, 'b': 2}
d.pop('a') # 1
d.pop('z', 0) # 0dict.setdefault(key[, default])If key is in the dict, return its value. Otherwise insert key with default and return default.
Parameters
| Name | Type | Description |
|---|---|---|
| key | Hashable | Key to look up. |
| default | Any | Value to insert if missing (default None). |
Returns
Any
Example
python
d = {'a': 1}
d.setdefault('a', 99) # 1
d.setdefault('b', 2) # 2
# d == {'a': 1, 'b': 2}