HOWTO · Python
How to Initialize a Dictionary in Python
This tutorial demonstrates how to initialize a dictionary in Python.
On this page
A Python dictionary stores key-value pairs, so a program can look up a value by its key. Choose the initialization pattern that matches your data: write a literal for known pairs, use dict() for supplied pairs or keyword arguments, use dict.fromkeys() for keys sharing one value, or derive entries with a comprehension. The examples below show how each form behaves.
Initialize a Dictionary with Literal Syntax
Use a dictionary literal when the keys and values are known in the code. Put each key and value inside braces, separated by a colon; separate pairs with commas. The resulting dictionary has unique keys; if a literal repeats a key, the last value assigned to that key is kept.
Run this example:
dict1 = {"X": 2, "Y": 3, "Z": 4}
print(dict1)
This creates three string keys mapped to integer values. A literal is usually the clearest choice for a small, fixed mapping.
Initialize a Dictionary with the dict() Constructor
The dict() constructor accepts keyword arguments or an iterable of key-value pairs. Keyword names become string keys, so use pair input when keys are not valid identifiers or are not strings. For example, dict(X=1, Y=2) creates the same mapping as {"X": 1, "Y": 2}. To convert existing pairs, pass them as an iterable, such as dict([("X", 1), ("Y", 2)]).
The constructor is useful when data already arrives as pairs. If a pair sequence repeats a key, the later pair supplies the value kept for that key.
Use dict.fromkeys() for Keys with a Shared Default
dict.fromkeys() creates a new dictionary from an iterable of keys and assigns each key the same supplied value. If you omit the value, it uses None, as in dict.fromkeys(["X", "Y", "Z"]).
This is convenient for immutable defaults such as None, 0, or a string. Be careful with a mutable value such as a list: every key refers to that same list object, so changing it through one key is visible through the others. When each key needs an independent mutable value, use a comprehension such as {key: [] for key in keys} instead.
Build a Dictionary from Pairs or Parallel Iterables
If records already contain key-value pairs, pass the iterable directly to dict(). A list of tuples works, as does another iterable whose items each contain two values: dict([("X", 5), ("Y", 6), ("Z", 8)]).
When keys and values are stored separately, pair them with zip() and pass the pairs to dict(). For example, dict(zip(["X", "Y", "Z"], [5, 6, 8])) maps each key to the value at the same position. zip() stops as soon as either iterable is exhausted, so extra items in the longer iterable are not included. If a resulting pair repeats a key, the last value wins.
Create a Dictionary with a Comprehension
A dictionary comprehension derives entries from an iterable in one expression. Its general shape is {key_expression: value_expression for item in iterable}. For example, {name: 0 for name in ["Ada", "Lin"]} gives each name an initial value of zero.
Use a comprehension when values or keys are calculated from input, or when each key needs its own newly created mutable value. It is equivalent to starting with an empty dictionary and assigning a value for each item in a loop. Keep the expression straightforward; a regular loop is easier to read when the transformation has several steps.
Add a Default for a Missing Key with setdefault()
setdefault() operates on an existing dictionary. It returns the current value when the key is present; otherwise, it inserts the key with the supplied default and returns that value. For example, counts.setdefault("apples", 0) initializes a missing counter while preserving an existing count.
This method is useful when a dictionary already exists and a particular key may need initialization. It is not a constructor for a complete mapping. For repeated grouping of values, consider setdefault(key, []) with care: the new list is created for the call, and subsequent calls for an existing key return its current list. Direct calls to __setitem__() are a low-level alternative; ordinary assignment such as mapping[key] = value is clearer for setting one entry.
Choose the Right Dictionary Initialization Pattern
Use a literal for a small mapping whose pairs are known in advance. Choose dict() for keyword arguments or existing pair data, and pair parallel iterables with zip() when the positions correspond. Use dict.fromkeys() when all keys should refer to one shared default, especially an immutable value. Choose a comprehension for calculated entries or separate per-key values. Use setdefault() to add a default to a key in a dictionary you already have.