On this page
dict
Prev: delattr | Up: __builtins__ | Next: dir
Rel: bool, int, float, complex, str
Ref: docs.python.org — dict
Tags: #public #python3 #builtins
Import & Availability
# Built-in (available globally without import)
from builtins import dict
Overview & Signature
dict() -> new empty dictionary
dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via:
Common Methods & Attributes
dict.clear(self, /)— Remove all items from the dict.dict.copy(self, /)— Return a shallow copy of the dict.dict.fromkeys(iterable, value=None, /)— Create a new dictionary with keys from iterable and values set to value.dict.get(self, key, default=None, /)— Return the value for key if key is in the dictionary, else default.dict.items(self, /)— Return a set-like object providing a view on the dict's items.dict.keys(self, /)— Return a set-like object providing a view on the dict's keys.dict.pop(...)— If the key is not found, return the default if given; otherwise, raise a KeyError.dict.popitem(self, /)— Remove and return a (key, value) pair as a 2-tuple.dict.setdefault(self, key, default=None, /)— Insert key with a value of default if key is not in the dictionary.dict.update(...)— If E is present and has a .keys() method, then does: for k in E.keys(): D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k]dict.values(self, /)— Return an object providing a view on the dict's values.
Usage
d = dict(a=1, b=2) | {"c": 3}
assert list(d.keys()) == ["a", "b", "c"]
assert d.get("missing", 0) == 0
Gotchas
- Preserves insertion order (guaranteed since Python 3.7): Keys must be hashable (
listanddictcannot be keys). - Never mutate keys while iterating: Iterate over
list(d)if deleting keys in a loop.
REPL Inspect
help(dict)
Linked from
Related notes
- tuts/python3/__builtins__/__builtins__ Linked here; links to this page; shared tags: #builtins
- tuts/python3/__builtins__/delattr Linked here; links to this page; shared tags: #builtins
- tuts/python3/__builtins__/dir Linked here; links to this page; shared tags: #builtins
- tuts/python3/__builtins__ links to this page; shared tags: #builtins
- tuts/python3/__builtins__/bool Linked here; shared tags: #builtins
- tuts/python3/__builtins__/complex Linked here; shared tags: #builtins
- tuts/python3/__builtins__/float Linked here; shared tags: #builtins
- tuts/python3/__builtins__/int Linked here; shared tags: #builtins
- tuts/python3/__builtins__/str Linked here; shared tags: #builtins
- tuts/python3 links to this page