A Python dictionary is a collection of key-value pairs. You look up a value by its key instead of by its position, the way you look up a phone number by someone’s name. Keys are unique, and the type is called dict. You write a dictionary with curly braces, with a colon between each key and its value:
>>> phone_numbers = {'Jack': '070-02222748', 'Pete': '010-2488634'}
>>> phone_numbers['Jack']
'070-02222748'Code language: Python (python)
In other programming languages and computer science in general, dictionaries are also known as associative arrays, maps or hash maps. If you are familiar with JSON, you might feel right at home: the syntax of a dictionary strongly resembles that of a JSON document.
How to create a dictionary in Python
There are five common ways to create a dictionary in Python. Here they are side by side in the Python REPL, each building the same small dictionary of names and ages (except the comprehension, which computes its values):
>>> {'Jack': 32, 'Pete': 41}
{'Jack': 32, 'Pete': 41}
>>> dict(Jack=32, Pete=41)
{'Jack': 32, 'Pete': 41}
>>> dict([('Jack', 32), ('Pete', 41)])
{'Jack': 32, 'Pete': 41}
>>> names = ['Jack', 'Pete']
>>> ages = [32, 41]
>>> dict(zip(names, ages))
{'Jack': 32, 'Pete': 41}
>>> {name: len(name) for name in names}
{'Jack': 4, 'Pete': 4}
>>> dict.fromkeys(names, 0)
{'Jack': 0, 'Pete': 0}Code language: Python (python)
- Curly braces (a dictionary literal) are what you’ll use most. Use them whenever you can type the data out.
dict()turns keyword arguments or a list of pairs into a dictionary.dict(zip(keys, values))combines two lists: one with keys, one with values.- A dictionary comprehension builds a dictionary from any iterable, computing keys and values as it goes.
dict.fromkeys()gives a list of keys the same starting value.
Each of these is explained in more detail below.
Create a dictionary with curly braces
A dictionary is created by using curly braces. Inside these braces, you add one or more key-value pairs, separated by commas. The dictionary below associates keys (names like Jack and Pete) with values (their phone numbers). The second one, my_empty_dict, is an empty dictionary:
>>> phone_numbers = {
... 'Jack': '070-02222748',
... 'Pete': '010-2488634',
... }
>>> my_empty_dict = {}
>>> phone_numbers['Jack']
'070-02222748'
>>> type(my_empty_dict)
<class 'dict'>Code language: Python (python)
When a dictionary gets longer than one line, put each pair on its own line like I did here. A comma after the last pair is allowed, and it makes adding another pair later a little easier.
One thing that trips people up: {} is an empty dictionary, not an empty set. For an empty set, you need set():
>>> type({})
<class 'dict'>
>>> type(set())
<class 'set'>Code language: Python (python)
If you’d like to practice this with exercises that check your code as you go, the lesson Create and Read a Dictionary in my Python Fundamentals course covers exactly this.
More ways to create a Python dictionary
Depending on where your data comes from, one of these other ways to create a dictionary might come in handy.
Using the dict() constructor
The dict() function can build a dictionary from keyword arguments, or from a sequence of key-value pairs (tuples). Called without arguments, it returns an empty dictionary:
>>> dict(name='Erik', language='Python', years=20)
{'name': 'Erik', 'language': 'Python', 'years': 20}
>>> dict([('Jack', '070-02222748'), ('Pete', '010-2488634'), ('Eric', '06-10101010')])
{'Jack': '070-02222748', 'Pete': '010-2488634', 'Eric': '06-10101010'}
>>> dict()
{}Code language: Python (python)
The keyword version saves you some quotes, but it only works when your keys are strings that are also valid Python names. A key like 'first-name' or 2024 needs the curly-brace syntax.
Create a dictionary from two lists with zip()
If you have one list with keys and another with values, zip() pairs them up, and dict() turns those pairs into a dictionary:
>>> names = ['Jack', 'Pete', 'Eric']
>>> numbers = ['070-02222748', '010-2488634', '06-10101010']
>>> dict(zip(names, numbers))
{'Jack': '070-02222748', 'Pete': '010-2488634', 'Eric': '06-10101010'}Code language: Python (python)
Be careful when the lists don’t have the same length. By default, zip() silently stops at the shortest list, so data goes missing without a warning. Pass strict=True (Python 3.10 and later) to get an error instead:
>>> dict(zip(['a', 'b', 'c'], [1, 2]))
{'a': 1, 'b': 2}
>>> dict(zip(['a', 'b', 'c'], [1, 2], strict=True))
Traceback (most recent call last):
File "<python-input-1>", line 1, in <module>
dict(zip(['a', 'b', 'c'], [1, 2], strict=True))
~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
ValueError: zip() argument 2 is shorter than argument 1Code language: Python (python)
Dictionary Comprehensions
Analogous to list comprehensions, you can also use dictionary comprehensions to create a new dictionary. While a list only contains values, a dictionary contains key-value pairs. Hence, a dictionary comprehension needs to define both, separated by a colon. Other than that, the syntax is similar: