Python dictionary is an associative container that contains the items in key/value pairs. In Python, there are Different Ways to Initialize Dictionary.
- Initialize an empty dictionary.
- Define dict with initial None values.
- Initialize Dictionary using dict constructor.
- Initialize dictionary using dict() and zip() methods
- Using defaultdict.
- Using setdefault.
How to initialize an empty dictionary in Python
To initialize an empty dictionary in Python:
- Initialize dict using {}(blank curly braces)
- Use dict() function and don’t pass anything.
# Creating an empty dict using empty brackets emptyDict = {} print(emptyDict) # Creating an empty dict using dict() blankDict = dict() print(blankDict)
Output
{} {}
Initialize dictionary with None values
To initialize a dictionary with None values in Python, use the dict.fromKeys() function. The dictionary fromKeys() function creates a new dictionary from the given sequence of items with a value provided by the user.
See the following code.
empty_dict = dict.fromkeys(['company', 'revenue']) print(empty_dict)
Output
{'company': None, 'revenue': None}
Use the dict.fromkeys() function to initialize a dictionary with any default value. In our case, we will initialize with None since we don’t have a default value in mind.
Initialize dict with the same values
We can also define a dictionary with the same values.
listKeys = ["company", "revenue", "employees"] sameValued = dict.fromkeys(listKeys, 0) print(sameValued)
Output
{'company': 0, 'revenue': 0, 'employees': 0}
Initialize with Dictionary constructor
To initialize a dictionary using constructor, passing key-value pairs in the dictionary constructor. We will define a key of the Dictionary, but we will put an empty list in values.
See the following code.
empty_list_dict = dict(company=[], revenue=[]) print(empty_list_dict)
Output
{'company': [], 'revenue': []}
From the output, you can see that we have defined a dictionary with empty lists.
Initialize dictionary using dict() and zip() methods
Python zip() function returns the zip object, which is the iterator of tuples. Then, we have converted the iterator of tuples into Dictionary, return, and print the Dictionary.
listKeys = ["company", "revenue", "employees"] # using zip() function to create a dictionary # with keys and same length None value dctnry = dict(zip(listKeys, [None]*len(listKeys))) # print dict print(dctnry)
Output
{'company': None, 'revenue': None, 'employees': None}
From the output, you can see that the values are None. So, this is also another example of how you can define None valued Dictionary in Python.
Using defaultdict
This is the most pythonic way and error-free way to use any key without initialization of its value, and it has to be told the type of default container of all its keys and then evaluates the operations and structures accordingly.
See the following code.
from collections import defaultdict # initializing dict with lists new_dict = defaultdict(list) # performing append # shows no error new_dict[0].append('company') # printing result print("Dictionary initialized : " + str(dict(new_dict)))
Output
Dictionary initialized : {0: ['company']}
Using setdefault
Python setdefault() method can be used to perform this by specifying key-value pairs within a comprehension.
See the following code.
new_dict = {} [new_dict.setdefault(x, []) for x in range(3)] # performing append # shows no error new_dict[0].append('company') # printing result print ("New dictionary created : " + str(dict(new_dict)))
Output
New dictionary created : {0: ['company'], 1: [], 2: []}
Conclusion
As we have discussed, there are so many ways that you can initialize the dictionaries. For example, you can define with 0, None, Same values, empty list, literals using various methods.