Set a list default value for dictionary keys in Python

avatar

Borislav Hadzhiev

Last updated: Sep 17, 2022

banner

Photo from Unsplash

Set a list default value for dictionary keys in Python #

Use the defaultdict class to set a list as the default value for a dictionary's keys, e.g. my_dict = defaultdict(list). The defaultdict class will return a list instead of raising a KeyError for non-existent keys in the dictionary.

main.py
from collections import defaultdict my_dict = defaultdict(list) my_dict['site'].append('bobbyhadz.com') # 👇️ defaultdict(<class 'list'>, {'site': ['bobbyhadz.com']}) print(my_dict) print(my_dict['tasks']) # 👉️ [] # 👇️ defaultdict(<class 'list'>, {'site': ['bobbyhadz.com'], 'tasks': []}) print(my_dict)

We passed the list() class to the defaultdict class to use a list as the default value for keys that don't exist in the dictionary.

The first argument the defaultdict class takes is a function that returns the default value for all keys.

The defaultdict class returns the specified default value when a non-existent key is accessed.

If you access a non-existent key in a regular dictionary, you'd get a KeyError exception.

If you have to set a list as the default value for an existing dictionary, pass a second argument to the defaultdict() class.

main.py
from collections import defaultdict my_dict = { 'name': 'Borislav Hadzhiev', 'id': 1, } # ✅ pass existing dictionary as second argument to defaultclass() my_dict = defaultdict(list, my_dict) my_dict['site'].append('bobbyhadz.com') # 👇️ defaultdict(<class 'list'>, {'name': 'Borislav Hadzhiev', 'id': 1, 'site': ['bobbyhadz.com']}) print(my_dict) print(my_dict['tasks']) # 👉️ [] # 👇️ defaultdict(<class 'list'>, {'name': 'Borislav Hadzhiev', 'id': 1, 'site': ['bobbyhadz.com'], 'tasks': []}) print(my_dict)

The second argument the defaultclass takes is optional and can be a dictionary or a list of key-value pairs.

Trying to access any key that doesn't exist in the dictionary now returns a list.

You can directly use list methods on non-existent keys.

Alternatively, you can use the setdefault() method.

Set a list default value for dictionary keys using setdefault() #

To set a list as the default value for a dictionary's keys:

  1. Store the keys of the dictionary in a list.
  2. Use a for loop to iterate over the list of keys.
  3. Use the setdefault() method to set a list as the default value for each key.
main.py
my_dict = { 'names': ['alice', 'bobbyhadz', 'carl'] } keys = ['tasks', 'numbers', 'names'] for key in keys: my_dict.setdefault(key, []) # 👇️ {'names': ['alice', 'bobbyhadz', 'carl'], 'tasks': [], 'numbers': []} print(my_dict)

The setdefault method takes a key and a default value as arguments.

If the key is in the dictionary, the method returns its value.

If the key is not in the dictionary, the method inserts the key with the specified value.

When using the setdefault method, you have to know the keys of the dictionary ahead of time, which makes the method less flexible than the defaultdict class.

The setdefault method is mainly used when you have an empty dictionary and know the names of all keys the dictionary will store.

Then you can iterate over the collection of keys and set a default value for each key.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.