Set default value for all keys in dictionary in Python

avatar

Borislav Hadzhiev

Last updated: Sep 17, 2022

banner

Photo from Unsplash

Set default value for all keys in dictionary in Python #

Use the defaultdict class to set a default value for all keys in a dictionary, e.g. my_dict = defaultdict(lambda: [], my_dict). The defaultdict class returns the specified default value instead of raising a KeyError for non-existent keys.

main.py
from collections import defaultdict my_dict = { 'name': 'Borislav Hadzhiev', 'site': 'bobbyhadz.com', 'id': 1, } my_dict = defaultdict(lambda: [], my_dict) # 👇️ defaultdict(<function <lambda> at 0x7f4cc7950f70>, {'name': 'Borislav Hadzhiev', 'site': 'bobbyhadz.com', 'id': 1}) print(my_dict) my_dict['tasks'].append('dev') print(my_dict['tasks']) # 👉️ ['dev'] print(my_dict['another']) # 👉️ [] # 👇️ defaultdict(<function <lambda> at 0x7f4cc7950f70>, {'name': 'Borislav Hadzhiev', 'site': 'bobbyhadz.com', 'id': 1, 'tasks': ['dev'], 'another': []}) print(my_dict)

We used a list as the default value for all keys in the dictionary but you can use any other value.

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

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

If you don't have an existing dictionary, omit the second argument in the call to defaultdict().
main.py
from collections import defaultdict my_dict = defaultdict(lambda: []) # 👇️ defaultdict(<function <lambda> at 0x7f71a66c3d90>, {}) print(my_dict) my_dict['tasks'].append('dev') print(my_dict['tasks']) # 👉️ ['dev'] print(my_dict['another']) # 👉️ [] # 👇️ defaultdict(<function <lambda> at 0x7f71a66c3d90>, {'tasks': ['dev'], 'another': []}) print(my_dict)

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.

Alternatively, you can use the dict.setdefault() method.

Set default value for all keys in dictionary using setdefault() #

To set a default value for all keys in a dictionary:

  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 default value for each key.
main.py
my_dict = { 'name': 'Borislav Hadzhiev', 'site': 'bobbyhadz.com', 'id': 1, } keys = ['name', 'tasks', 'salary'] for key in keys: my_dict.setdefault(key, 'default value') # ️{'name': 'Borislav Hadzhiev', # 'site': 'bobbyhadz.com', # 'id': 1, # 'tasks': 'default value', # 'salary': 'default value'} 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.

If you don't specify a default value, None is used.

main.py
my_dict = { 'name': 'Borislav Hadzhiev', 'site': 'bobbyhadz.com', 'id': 1, } keys = ['name', 'tasks', 'salary'] for key in keys: my_dict.setdefault(key) # ️{'name': 'Borislav Hadzhiev', # 'site': 'bobbyhadz.com', # 'id': 1, # 'tasks': None, # 'salary': None} print(my_dict)

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.

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.