AppDividend
Latest Code Tutorials

Different Ways to Initialize Dictionary in Python

0

Python dictionary is an associative container that contains the items in key/value pairs. In Python, there are Different Ways to Initialize Dictionary.

  1. Initialize an empty dictionary.
  2. Define dict with initial None values.
  3. Initialize Dictionary using dict constructor.
  4. Initialize dictionary using dict() and zip() methods
  5. Using defaultdict.
  6. Using setdefault.

How to initialize an empty dictionary

We can create an empty dictionary using the following two ways.

  1. Initialize dict using {}(blank curly braces)
  2. 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

We can use dict.fromkeys() function to initialize dictionary with None values.

Python 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

We can initialize a dictionary by passing key-value pairs in dictionary constructor,

We will define a key of the Dictionary, but in values, we will put an empty list.

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. You can define with 0, None, Same values, empty list, literals using various methods.

See also

Dictionary update()

Dictionary values()

Dictionary popitem()

Dictionary items()

Convert Dictionary to DataFrame

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.