Back to articles list Articles
6 minutes read

5 Ways to Create a Dictionary in Python

Want to step up your Python game? Learn how to create dictionaries in Python from many different sources, including reading from JSON files and combining two dictionaries.

So, you've already figured out how to use dictionaries in Python. You know all about how dictionaries are mutable data structures that hold key-value pairs. You understand you must provide a key to the dictionary to retrieve a value. But you may not have realized dictionaries in Python come in all shapes and sizes and from all kinds of sources.

Just think about how many real-life objects can be modeled using key-value pairs: students and their grades, people and their occupations, products and their prices, just to name a few. Dictionaries are central to data processing in Python, and you run into them when loading data from files or retrieving data from the web.

Since Python dictionaries are so ubiquitous, it is no surprise you can build them from many different sources. In this article, we explore 5 ways to create dictionaries in Python. Let’s get started!

1. Python Dictionary From the Dictionary Literal {}

Not surprisingly, this is the most common method for creating dictionaries in Python. All you have to do is declare your key-value pairs directly into the code and remember to use the proper formatting:

  • Use { to open the dictionary.
  • Use : to define key-value pairs.
  • Use , to separate key-value pairs from each other.
  • Use } to close the dictionary.

Simple, but effective! Here’s a basic example of how this looks:

grades = {'John': 7.5, 'Mary': 8.9, 'James': 9.0}

Dictionaries ignore spaces and line breaks inside them. We can take advantage of this and write just one key-value pair per line. It improves readability, especially when our dictionaries grow a little too big to fit comfortably in a single line:

grades = {
    'John': 7.5,
    'Mary': 8.9,
    'James': 9.0,
    # add more lines here …
}

2. Python Dictionary From the dict() Constructor

Dictionaries can also be built from the Python dict() constructor. dict() is a built-in function in Python, so it is always available to use without the need to import anything.

You can use the Python dict() constructor in two ways. The first is to provide the key-value pairs through keyword arguments:

prices = dict(apple=2.5, orange=3.0, peach=4.4)
print(prices)

# output: {'apple': 2.5, 'orange': 3.0, 'peach': 4.4}

It’s fair to say the first method is easier to read and understand at a glance. However, keyword arguments are always interpreted as strings, and using keyword arguments may not be an option if you need a dictionary in which the keys are not strings. Take a look at this example to see what I mean:

# this works
values = [(1, 'one'), (2, 'two')]
prices = dict(values)

# SyntaxError - a number is not a valid keyword argument!
prices = dict(1='one', 2='two')

By the way, if you need a reminder, check out this great article on tuples and other sequences in Python.

3. Python Dictionary From a JSON File

JSON stands for JavaScript Object Notation, and it is an extremely common file format for storing and transmitting data on the web. Here’s an example JSON file, called person.json:

{
    "name": "Mark",
    "age": 32,
    "likes_dancing": true
}

Notice anything? Yep! JSON files are pretty much identical to dictionaries in Python. So, it is no surprise you can load JSON data into Python very easily. We simply need to:

  • Import the json module (don’t worry about installing anything; this module is part of Python’s base installation).
  • Open the person.json file (take a look at this course if you don’t know what “opening a file” means in Python).
  • Pass the open file handle to the json.load() function.

We take these steps in the code below:

import json

with open('person.json', 'r') as json_file:
    person = json.load(json_file)
print(person)

# output: {'name': 'Mark', 'age': 32, 'likes_dancing': True}

Note that you can also go the other way around and write a Python dict() into a JSON file. This process is called serialization. See this article for more information about serialization.

4. Python Dictionary From Two Dictionaries Using the Dictionary Union Operator

If you’re using Python version 3.9 or greater, there’s yet another way to create a dictionary in Python: the dictionary union operator (|), introduced in Python 3.9. It merges the key-value pairs of two or more dictionaries into a single one. In that sense, it is similar to the set union operator (read this article if you don’t know what set operators are).

Here’s an example of the dictionary union operator in action:

jobs_1 = {
	'John': 'Engineer',
	'James': 'Physician',
}

jobs_2 = {
	'Jack': 'Journalist',
	'Jill': 'Lawyer',
}

jobs = jobs_1 | jobs_2
print(jobs)

# output: {'John': 'Engineer', 'James': 'Physician', 'Jack': 'Journalist', 'Jill': 'Lawyer'}

It’s important to note that, if there are duplicate keys in the source dictionaries, the resulting dictionary gets the value from the right-most source dictionary. This is a consequence of Python not allowing duplicate keys in a dictionary. Take a look at what happens here:

d1 = {
	'A': 1,
	'B': 2,
}

d2 = {
	'B': 100,
	'C': 3,
}

result = d1 | d2
print(result)

# output: {'A': 1, 'B': 100, 'C': 3}

As you can see, B appears in both d1 and d2. The value in the result dictionary comes from d2, the right-most source dictionary in the expression d1 | d2. The key-value pair 'B': 2 from d1 is lost. Keep this in mind when using the dictionary union operator!

5. Python Dictionary From a Dict Comprehension

Have you heard of list comprehensions? Once you get the hang of them, they are a great way to create new lists from already existing ones, either by filtering the elements or modifying them.

But what does it have to do with building dictionaries in Python? Well, a similar syntax is used for constructing dictionaries, in what we call a dict comprehension. In the example below, we take a list of strings and build a dictionary from them. Each key is the string itself, and the corresponding value is its length. Take a look:

animals = ['cat', 'lion', 'monkey']
animal_dict = {animal: len(animal) for animal in animals}
print(animal_dict)

# output: {'cat': 3, 'lion': 4, 'monkey': 6}

See how it works? For each animal in the list animals, we build a key-value pair of the animal itself and its length (len(animal)).

Here’s a more intricate example. We use a dict comprehension to filter the values from a preexisting dictionary. See if you can figure out what the code below does:

ages = {
    'Bill': 23,
    'Steve': 34,
    'Maria': 21,
}
filtered_ages = {name: age for name, age in ages.items() if age < 30}
print(filtered_ages)

# output: {'Bill': 23, 'Maria': 21}

Do you see what happens? We use ages.items() to get each key-value pair from the original dictionary and build filtered_ages based on that. But we add the if age < 30 bit at the end. So, during its construction, filtered_ages ignores the key-value pairs where the age is equal to or greater than 30. In other words, we filter the original dictionary, selecting only the key-value pairs where the value is less than 30. That’s some powerful stuff!

Create Dictionaries in Python!

In this article, we discussed 5 ways to create dictionaries in Python. We went from the very basics of the dictionary literal {} and the Python dict() constructor, to more complex examples of JSON files, dictionary union operators, and dict comprehensions.

Hope you learned something new. If you want more, be sure to go to LearnPython.com for all things related to Python!