How to append to list in python dictionary

Published by user on

In this post, we are going to look at how to append values to the list in python dictionary. Also, we will look at how to add key in the dictionary if not already present.

What scenario does the dictionary of list solve?

Consider a scenario where we want to represent the list of favorite colors for each user.

E.g. If John’s favorite colors are ‘red’, ‘pink’, and ‘green’, then we are going to represent it as.

{‘John’: [‘red’, ‘pink’, ‘green’]}

To represent the above scenario in python we can use the dictionary of list.

Check if the key is present in the dictionary

Let’s look at how to check if the key is already present in the dictionary.

user_color = dict()

if "john" in user_color:
print('John is present in the dictionary')
print('John is not present in the dictionary')


John is not present in the dictionary

Append value to the list

Now when we want to add the First color for John, then there is no key present for him. Let’s look at how to add the key to the dictionary and append values in the list.

Add key manually to the dictionary

user_color["john"] = ["red"]

But there is a better way provided by python using collections.defaultdict(list).

Let’s look at the program using defaultdict.

from collections import defaultdict
user_color = defaultdict(list)




defaultdict(<class 'list'>, {'john': ['red', 'pink', 'green']})

Using defaultdict, we don’t have to initialize the key with an empty list. If the key is not already present in the dictionary then python creates a new key for us.

As you can see ‘john’ was not present in the dictionary but still, python didn’t complain. It created a new key and then added colors to the list.

Categories: python