Python Glossary Русский

all Python 3Dictionaries (dict)term

Creating a dictionary

creation

A dictionary is written as a {k: v} literal, or built with dict(), dict.fromkeys() or a dict comprehension.

Syntax

{}  |  dict()  |  {k: v}  |  dict.fromkeys(keys[, val])

{} is an empty dict, never an empty set — that one is only set(). In dict.fromkeys(keys, []) the value is evaluated once, so every key ends up bound to the very same list and an append through one key appears under all of them; use a dict comprehension when each value must be its own mutable object. The dict(a=1) form only accepts keys that are valid identifiers, so arbitrary strings need the literal.

Examples

d1 = {}
# → {}
d2 = {'a': 1, 'b': 2}
# → {'a': 1, 'b': 2}
d3 = dict(x=1, y=2)
# → {'x': 1, 'y': 2}
d4 = dict([('a', 1), ('b', 2)])
# → {'a': 1, 'b': 2}
d5 = dict.fromkeys(['a', 'b', 'c'], 0)
print(d5)
# → {'a': 0, 'b': 0, 'c': 0}
d6 = dict.fromkeys('abc')
print(d6)
# → {'a': None, 'b': None, 'c': None}
d7 = {i: i**2 for i in range(4)}
print(d7)
# → {0: 0, 1: 1, 2: 4, 3: 9}

See also

Open in the full glossarydocs.python.orgReport an inaccuracy