Skip to content

Python Dict API

Python dict methods — mutable mapping of hashable keys to values.

1 class · 7 methods

dict

7 methods

Mutable 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

NameTypeDescription
keyHashableKey to look up.
defaultAnyValue 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)    # 0
dict.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

NameTypeDescription
otherdict | Iterable[(k, v)] | MappingSource 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

NameTypeDescription
keyHashableKey to remove.
defaultAnyReturned if key is missing.

Returns

Any

Example

python
d = {'a': 1, 'b': 2}
d.pop('a')       # 1
d.pop('z', 0)    # 0
dict.setdefault(key[, default])

If key is in the dict, return its value. Otherwise insert key with default and return default.

Parameters

NameTypeDescription
keyHashableKey to look up.
defaultAnyValue 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}