In this Python tutorial, I will explain how to initialize Python dictionary with keys and values using different methods with illustrative examples. In the process, I will also show what is a dictionary in Python and why we need to initialize a dictionary in Python.
Python, a highly versatile and popular programming language, provides a variety of data structures. One of the most useful among them is the dictionary.
What is a Dictionary in Python?
Before diving into the initialization methods, it’s crucial to understand what a Python dictionary is. In Python, a dictionary is an unordered collection of data in a key-value pair form. Here’s a simple example: if we wanted to represent the population of a few US cities, we could use a dictionary:
population = {
"New York": 8175133,
"Los Angeles": 3792621,
"Chicago": 2695598
}
What is meant by “Initialize Python dictionary with keys and values”?
When we say “initialize a dictionary with keys and values,” we are referring to the action of creating a new Python dictionary and setting it up with a predefined set of keys, each associated with a specific value. Essentially, it’s about preparing or setting up a Python dictionary with some initial data.
Let’s break it down with an example for better understanding:
Suppose we want to represent the age of three individuals: Alice, Bob, and Charlie.
To initialize a Python dictionary with their names as keys and their ages as values, we would do the following:
ages = {
"Alice": 28,
"Bob": 34,
"Charlie": 22
}
In the above code, we’ve “initialized” the “ages
” Python dictionary with certain keys (names) and their corresponding values (ages). This means that the Python dictionary “ages
” now holds this initial data, and we can use, modify, or build upon this data as needed in our program.
Ways to initialize Python dictionary with keys and values
There are six different ways present in Python initialize dict with keys and values:
- Direct method
- Using
dict()
Constructor - Using Dictionary Comprehension
- Using for loop
- Using
dict.fromkeys()
- Using
defaultdict
from collection
Let’s see them one by one with some demonstrative examples:
Method-1: Python Initialize Dictionary with Keys and Values Directly
This is the most straightforward Python method, as shown in the example above. We just enclose our key-value pairs in curly {} braces.
For instance, Representing the number of Super Bowl wins by a few NFL teams.
super_bowl_wins = {
"New England Patriots": 6,
"Pittsburgh Steelers": 6,
"San Francisco 49ers": 5
}
print(super_bowl_wins)
print(type(super_bowl_wins))
Here, the teams are the keys, and their respective Super Bowl wins are the values. By placing these inside curly braces, we create a Python dictionary directly.
The output is: Here we are printing first the Python dictionary we created and then checking whether it actually belongs to the dictionary data type in Python or not, using the type() Python method.
{'New England Patriots': 6, 'Pittsburgh Steelers': 6, 'San Francisco 49ers': 5}
<class 'dict'>
This way we can initialize Python dictionary with keys and values directly.
Method-2: Initialize Dictionary Python the Using dict() Constructor
Python provides the dict()
constructor which allows us to initialize a dictionary in Python using keyword arguments or an iterable.
Let’s take a scenario of representing the founding states of some well-known US universities.
universities = dict(Harvard="Massachusetts", Stanford="California", Yale="Connecticut")
print(universities)
print('The variable \'universities\' belong to', type(universities))
The dict() constructor takes key-value pairs and returns a Python dictionary. Here, universities are keys, and their founding states are values.
The output is: Here a new Python dict will be initialized with the keys and values.
{'Harvard': 'Massachusetts', 'Stanford': 'California', 'Yale': 'Connecticut'}
The variable 'universities' belongd to <class 'dict'>
This way we can initialize a dictionary Python using the dict() constructor.
Method-3: Python Initialize Dictionary with Keys Using Dictionary Comprehension
If we have a list of keys and we want to initialize Python dictionary with keys and default value, dictionary comprehension is a fantastic tool.
For example, Cataloging the favorite foods of a few US presidents but not yet knowing what they are. so setting it with “Unknown” as the default value.
presidents = ['Abraham Lincoln', 'George Washington', 'John Adams']
favorite_foods = {president: 'Unknown' for president in presidents}
print(favorite_foods)
Dictionary comprehension in Python allows us to create a new dictionary from an iterable (in this case, a list of presidents). Each president is initialized with a default value of “Unknown”.
The output is: Printing the Python dictionary created
{'Abraham Lincoln': 'Unknown', 'George Washington': 'Unknown', 'John Adams': 'Unknown'}
This way we can Python initialize dictionary with keys and default value.
Method-4: Using a for loop to initialize dict Python
Using a for
loop to initialize a dictionary in Python offers a straightforward method to map corresponding elements from two Python lists into key-value pairs in a Python dictionary. This method is particularly useful when dealing with parallel lists of data.
For instance, Consider that we have a list of American cities and another list of the respective state each city is located in. We wish to create a dictionary where each city (key) points to its state (value) in Python.
cities = ['Chicago', 'Los Angeles', 'Houston', 'Phoenix', 'Philadelphia']
states = ['Illinois', 'California', 'Texas', 'Arizona', 'Pennsylvania']
city_with_state = {}
for i in range(len(cities)):
city_with_state[cities[i]] = states[i]
print(city_with_state)
In this example, we’ve initialized an empty Python dictionary named city_with_state
. We then used a for
loop to iterate over the length of the cities
list. For each iteration, we added a new key-value pair to the dictionary, where the key is a city from the cities
list and the value is the corresponding state from the states
list.
The output is: After executing the loop, the city_with_state
Python dictionary will look like this:
{'Chicago': 'Illinois', 'Los Angeles': 'California', 'Houston': 'Texas', 'Phoenix': 'Arizona', 'Philadelphia': 'Pennsylvania'}
This way we can use for loop to initialize dictionary Python.
Method-5: Using dict.fromkeys() to Python init dict with keys and values
The dict.fromkeys()
method allows us to initialize dict python with a list of keys and a single default value.
For instance, Tracking the number of Oscars won by some famous American directors.
directors = ['Martin Scorsese', 'Steven Spielberg', 'Quentin Tarantino']
oscar_wins = dict.fromkeys(directors, 0)
print(oscar_wins)
The fromkeys() Python method initializes a new Python dictionary with keys from the provided list (directors) and assigns the same default value (0) to each of them.
The output is:
{'Martin Scorsese': 0, 'Steven Spielberg': 0, 'Quentin Tarantino': 0}
Python initialize dictionary with keys and default values using a dict.fromkeys() method.
Method-6: Python Initialize Dictionary with Default Value Using collections.defaultdict()
If we want a Python dictionary that automatically assigns a default value to any new key, the collections.defaultdict()
is handy.
For example, Trying to keep a tally of state visits by a US president during his term.
from collections import defaultdict
state_visits = ['Texas', 'Florida', 'Texas', 'California']
visit_count = defaultdict(int)
for state in state_visits:
visit_count[state] += 1
print(visit_count)
The defaultdict()
function from the collections module initializes a Python dictionary that assigns a default value (in this case, int which defaults to 0) to any new key. As we iterate over the state visits, the dictionary automatically handles new states or increments the count for states the president revisited.
The output is:
defaultdict(<class 'int'>, {'Texas': 2, 'Florida': 1, 'California': 1})
The Python dictionary initialize with keys and default values can be done with this defaultdict() function.
Why do we need to initialize a dictionary with keys and values?
Initialize Python dictionary with keys and values serves several practical purposes in programming, enhancing code clarity, efficiency, and robustness. Here are some reasons why initializing a dictionary with keys and values is beneficial:
- Structure and Organization: Dictionaries in Python allow data to be stored in a structured and organized manner. By initializing with keys and values, we can easily understand and predict the structure of our data.
- Data Lookup Efficiency: Python Dictionaries are implemented as hash tables. This means that looking up a value by its key is very efficient. Pre-populating a dictionary ensures that when we need to retrieve data, we can do so in constant time.
- Avoiding Key Errors: By pre-initializing a dictionary with certain keys, we can prevent potential KeyError exceptions in Python when trying to access keys that might not be present if added dynamically.
- Data Integrity: Initializing Python dictionaries with keys and values can serve as a form of documentation. A developer or user looking at the dictionary can instantly understand its intended structure and the kind of data it should store.
- Default Values: When we initialize a Python dictionary with keys and values, we often set default values for those keys. This can be helpful in scenarios where we need to ensure every key has some initial value, which can then be updated or modified based on subsequent operations.
Conclusion
In this tutorial, we have seen how to initialize Python dictionary with keys and values using different methods like using curly {} braces, dict() constructor, dictionary comprehension, for loop, dict.fromkeys(), or defaultdict() function with examples. We have also seen what is meant by a Python dictionary initialize with keys and values and why we need this.
A dictionary is an invaluable data structure in Python. Whether we want to initialize dictionary with default values, python init dict with keys and values, or any other specialized initialization, Python provides multiple ways to achieve it.
You may also like to read:
- Initialize dictionary Python with 0
- Remove key from dictionary Python
- Python dictionary fromkeys() method [With Examples]
- Python dictionary comprehension [7 methods]
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.