How to Initialize a Dictionary in Python?

In this tutorial, I will explain how to initialize a dictionary in Python. Recently in a webinar, someone asked me about initializing a dictionary in Python. After researching and experimenting I found a few efficient methods to accomplish this task. I will share my findings with suitable examples and screenshots.

Initialize a Dictionary in Python

The simplest and most common way to initialize a Python dictionary is to pass key-value pairs as literals in curly braces {} , separated by commas. Here’s an example:

person = {"name": "John Smith", "age": 35, "city": "New York"}

In this example, we create a dictionary called person with three key-value pairs. The keys are “name”, “age”, and “city”, and their corresponding values are “John Smith”, 35, and “New York”, respectively.

Read How to Get Keys of a Dictionary in Python?

Create an Empty Dictionary

Sometimes, you may need to create an empty dictionary and add key-value pairs later in your program. To create an empty dictionary, you can use the dict() constructor or simply use empty curly braces {}. Here’s how:

empty_dict = dict()
# or
empty_dict = {}

Both approaches create an empty dictionary called empty_dict. You can then add key-value pairs to the dictionary using the [] notation or the update() method.

Check out How to Save a Python Dictionary as a JSON File?

1. Initialize with Default Values

In some scenarios, you may want to initialize a dictionary with a specific set of keys and default values. Python provides the dict.fromkeys() method for this purpose. Here’s an example:

state_capitals = dict.fromkeys(["California", "Texas", "Florida"], "Unknown")
print(state_capitals)

Output:

{'California': 'Unknown', 'Texas': 'Unknown', 'Florida': 'Unknown'}

You can see the output in the screenshot below.

Initialize a Dictionary in Python

In this example, we initialize a dictionary called state_capitals with the keys “California”, “Texas”, and “Florida”, and set their default values to “Unknown”. This is useful when you have a predefined set of keys and want to assign a common default value to all of them.

Read How to Sum All Values in a Python Dictionary?

2. Initialize with User Input

In real-world scenarios, you may need to initialize a dictionary based on user input. Let’s say you’re building a program to store information about US states and their capitals. You can prompt the user to enter the state and capital, and then add them to the dictionary. Here’s an example:

us_states = {}
while True:
    state = input("Enter a US state (or 'done' to finish): ")
    if state == "done":
        break
    capital = input(f"Enter the capital of {state}: ")
    us_states[state] = capital

print(us_states)

Output:

{'California': 'Sacramento', 'Texas': 'Austin', 'Florida': 'Tallahassee'}

You can see the output in the screenshot below.

How to Initialize a Dictionary in Python

In this example, we initialize an empty dictionary called us_states. We then use a while loop to prompt the user to enter a US state and its capital. The state becomes the key, and the capital becomes the value in the Python dictionary. The loop continues until the user enters “done” to finish the input process.

Check out How to Search in Dictionary By Value in Python

3. Initialize with a List of Tuples

Another way to initialize a dictionary is by using a list of tuples, where each tuple represents a key-value pair. Here’s an example:

presidents = [("George Washington", 1789), ("John Adams", 1797), ("Thomas Jefferson", 1801)]
presidents_dict = dict(presidents)
print(presidents_dict)

Output:

{'George Washington': 1789, 'John Adams': 1797, 'Thomas Jefferson': 1801}

You can see the output in the screenshot below.

Initialize a Dictionary in Python List of Tuples

In this example, we have a list called presidents that contains tuples representing US presidents and their inauguration years. We pass this list to the dict() constructor to create a dictionary called presidents_dict. Each tuple becomes a key-value pair in the resulting dictionary.

Read How to Remove Multiple Keys from a Dictionary in Python?

4. Initialize with a Generator Expression

Python allows you to initialize a dictionary using a generator expression. This is useful when you want to create a dictionary based on a specific pattern or condition. Here’s an example:

squares = {x: x**2 for x in range(1, 6)}
print(squares)
# Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

In this example, we use a generator expression to create a dictionary called squares. The expression x: x**2 defines the key-value pair, where the key is x and the value is x squared. The for x in range(1, 6) part generates the values for x from 1 to 5.

Check out Write a Python Program to Remove Duplicates From a Dictionary

Conclusion

In this tutorial, I helped you learn how to initialize a dictionary in Python. I explained creating an empty dictionary, initializing with default values, initializing with user input, initializing with a list of tuples, and initialize with a generator expression.

You may read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.