Kodeclik Logo

Our Programs

Courses

Learn More

Schedule

Kodeclik Blog

Initializing a Python dictionary

Dictionaries are associative arrays mapping keys to values. They are very useful in many Python applications. In this blogpost, we will show you 8 different ways to initialize a Python dictionary.

Method 1: Initialize a Python dictionary with {}

The first way to initialize a Python dictionary is to give the list of key-value pairs within curly braces. For instance:

mydict = {'Apples': 3, 'Oranges': 2, 'Bananas': 6}
print(mydict)

This outputs:

{'Apples': 3, 'Oranges': 2, 'Bananas': 6}

This is the most straightforward way to initialize a Python dictionary.

Method 2: Initialize a Python dictionary with dict() constructor

The second way to initialize a Python dictionary is to use the dict() constructor. Note that in the syntax below, you input assignments of values to keys.

mydict = dict(Apples=3, Oranges=2, Bananas=6)

print(mydict)

The printed dictionary has the same format as before:

{'Apples': 3, 'Oranges': 2, 'Bananas': 6}

Method 3: Initialize a Python dictionary using list notation

We can also use a list of tuples and the dict constructor to make up a dictionary.

mydict = [('Apples', 3), ('Oranges', 2), ('Bananas', 6)]
print(mydict)
print(dict(mydict))

The output is:

[('Apples', 3), ('Oranges', 2), ('Bananas', 6)]
{'Apples': 3, 'Oranges': 2, 'Bananas': 6}

Note that in the first printed line, the output is a list of tuples. In the second printed line we see a dictionary because it uses the list as input to the dictionary.

Method 4: Initialize a Python dictionary using zip()

A fourth way to initialize a Python dictionary is to create two lists, one containing keys and one containing values, and use the zip() function to create pairs of (key,value) from corresponding entries of the two lists.

mykeys = ['Apples', 'Oranges', 'Bananas']
myvalues = [3,2,6]
  
print(dict(zip(mykeys,myvalues)))

The output is:

{'Apples': 3, 'Oranges': 2, 'Bananas': 6}

Method 5: Initialize a Python dictionary using fromkeys()

This method is applicable only if all keys have the same value (which is usually satisfied in some initialization settings). For instance, before you begin grocery shopping, values are zero for all the fruits. fromkeys() is a method applicable to the dict() class.

mykeys = ['Apples', 'Oranges', 'Bananas']

print(dict.fromkeys(mykeys,0))

The output is:

{'Apples': 0, 'Oranges': 0, 'Bananas': 0}

Method 6: Initialize a Python dictionary using dictionary comprehension

A variant of the above is to use dictionary comprehension to loop through the keys and assign an initial value. See for instance:

mykeys = ['Apples', 'Oranges', 'Bananas']

mydict = {x: 0 for x in mykeys}
print(mydict)

The output is as expected:

{'Apples': 0, 'Oranges': 0, 'Bananas': 0}

Method 7: Initialize a Python dictionary using list comprehension

This approach is a minor variant of the previous approach. We first initialize the dictionary to be an empty dictionary and use list comprehension syntax to set default values for keys.

mykeys = ['Apples', 'Oranges', 'Bananas']

mydict = {}
[mydict.setdefault(x,2) for x in mykeys]
  
print(mydict)

The output is the same as before:

{'Apples': 2, 'Oranges': 2, 'Bananas': 2}

Method 8: Initialize a Python dictionary using defaultdict()

Python Initialize Dictionary

In all of the above approaches, if you try accessing the dictionary with a non-existent key, you will get an error. For instance if you try:

mydict = {'Apples': 3, 'Oranges': 2, 'Bananas': 6}
print(mydict['Apples'])
print(mydict['Grapes'])

The output is:

3
Traceback (most recent call last):
  File "main.py", line 3, in <module>
    print(mydict['Grapes'])
KeyError: 'Grapes'

The final method for initializing a dictionary will never give such an error as it allows you to provide default values for non-existent keys. This method does not come with Python as default but comes as part of the collections package. It takes as input a function that returns a default value (here presented in lambda notation):

from collections import defaultdict

mydict = defaultdict(lambda: 0)
  
print(mydict['Grapes'])

The output is:

0

because the lambda function gives the default value as 0.

So there you have it - 8 different ways to initialize a Python dictionary! Which one is your favorite? Learn more about dictionaries in our posts about length of a dictionary, swapping positions of values in a dictionary, and about empty dictionaries in Python.

Interested in more things Python? See our blogpost on Python's enumerate() capability. Also if you like Python+math content, see our blogpost on Magic Squares. Finally, master the Python print function!

Want to learn Python with us? Sign up for 1:1 or small group classes.

Kodeclik sidebar newsletter

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.

About

Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.

Copyright @ Kodeclik 2024. All rights reserved.