fromkeys and setdefault methods – Python

Dictionary in Python can be created in multiple ways. In previous article, we learned about various ways to create dictionary in Python. We can also create dictionaries using built-in fromkeys(), copy() and setdefault() methods. In this article we will learn about these methods in detail.

Create dictionary – fromkeys() method

fromkeys() method is one of the ways to create dictionary in Python.

  • fromkeys() method take two arguments keys and default_value.
  • fromkeys() method is used to create a new dictionary with specified sequence of keys and a common default value assigned to all keys of the dictionary.
  • Since, all keys will be assigned the default value. We can also use a mutable object (like a list or dictionary) as the default value. But using a mutable object a default value should be carefully used.

Syntax of fromkeys() method:

dictionary = dict.fromkeys(keys_iterable, default_value)

  • keys_iterable (mandatory)keys_iterable is an iterable (like list, tuple, string) collection datatype. keys collection contains the keys for the dictionary elements.
  • Elements inside the keys_iterable should be of immutable datatypes like strings, numbers, or tuples. Mutable datatypes like lists cannot be used as keys of a dictionary.
  • default_value (optional): default_value is an optional argument. This is the default value which is assigned to each key (from key-value pairs) of the dictionary. If this value is not given, then None is considered as default_value.

Using fromkeys() with default_value

# create dictionary with default values using fromkeys method
print("create dictionary with default values using fromkeys method")
keys = (1, 2, 3, 4)
default_value = "Python"
courses = dict.fromkeys(keys, default_value)   # create dictionary using fromkeys() with default value
print(courses)
print(type(courses))

In this program, we have defined a tuple for keys and a default_value variable. We are using dict.fromkeys(keys, default_value) to create a new dictionary courses, where dictionary keys will be from tuple (1, 2, 3, 4) elements and value assigned will be default_value.

Program Output

create dictionary with default values using fromkeys method
{1: 'Python', 2: 'Python', 3: 'Python', 4: 'Python'}    # keys from tuple and default value to all keys
<class 'dict'>

From the output, a dictionary with 4 elements was created. Dictionary keys are from tuple (1, 2, 3, 4) and each key assigned default value Python.

Using fromkeys() without default_value

If the default value is not given, then None is considered as default_value.

# create dictionary with default values as None using fromkeys method
print("create dictionary with default values using fromkeys method")
keys = (1, 2, 3, 4)
courses = dict.fromkeys(keys)     # create dictionary using fromkeys() without default value
print(courses)
print(type(courses))

In this program, we have only defined a tuple for keys. We are using dict.fromkeys(keys) to create a new dictionary courses, where dictionary keys will be from tuple (1, 2, 3, 4) elements. Default value is not given, None will be considered as the default_value.

Program Output

create dictionary with default values using fromkeys method
{1: None, 2: None, 3: None, 4: None}
<class 'dict'>

From the output, a dictionary with 4 elements was created. Dictionary keys are from tuple (1, 2, 3, 4) and each key assigned default value None.

Using fromkeys() with String

# Creating a dictionary with characters from a string
char_dict = dict.fromkeys('shbytes', True)

print(char_dict)

Program Output

{'s': True, 'h': True, 'b': True, 'y': True, 't': True, 'e': True}

Access dictionary – setdefault() method

setdefault() method is a built-in function in Python and is used to access the elements from the dictionary.

  • setdefault() method take two arguments key and default_value.
  • If the key is present in the dictionary, then setdefault() method returns the value of that key from the dictionary.
  • If the key does not exist in the dictionary, then setdefault() inserts the key into the dictionary with a specified default value and returns that default value.

Syntax of setdefault() method:

return_value = dictionary.setdefault(key, default_value)

  • key (mandatory) – key is for which we want to get the value from the dictionary.
  • default_value (optional): default_value is an optional argument. This default value is assigned to the key if it does not exists in the dictionary. If this value is not given, then None is considered as default_value.
  • return_value – If key already exists in dictionary, then that key value will be returned else default_value will be returned.

Using setdefault() with default_value

  1. When key does not exists in dictionary – In this case new key-value pair will be inserted into the dictionary, with value as the given default_value.
  2. When key exists in dictionary – In this case key value from dictionary will be returned. No change in key-value.
# set default values to a key in dictionary
print("set default values to a key in dictionary")
language_dict = {"name": "Python", "popular": "Yes"}
print(language_dict)
return_value = language_dict.setdefault("learn", "Yes")   # using setdefault, key does not exists
print(language_dict)
print(return_value)

print("\n---------------------------------------------------\n")

# no impact of setdefault method if key is already present
print("no impact of setdefault method if key is already present")
language_dict = {"name": "Python", "popular": "Yes", "learn": "Yes"}
print(language_dict)
return_value = language_dict.setdefault("learn", "No")    # using setdefault, key exists
print(language_dict)
print(return_value)

In first scenario, defined language_dict dictionary has only two elements and key learn does not exist. Using language_dict.setdefault("learn", "Yes") will insert new key-value pair into the language_dict dictionary and default_value will be returned.

In second scenario, defined language_dict dictionary has three elements and key learn already exists in dictionary. Using language_dict.setdefault("learn", "No") will neither insert nor will make any update on the existing key-value pair into the language_dict dictionary and value for key learn from dictionary will be returned.

Program Output

set default values to a key in dictionary
{'name': 'Python', 'popular': 'Yes'}
{'name': 'Python', 'popular': 'Yes', 'learn': 'Yes'}   # new key-value pair added to dictionary
Yes    # returned value from new key-value pair 
---------------------------------------------------
no impact of setdefault method if key is already present
{'name': 'Python', 'popular': 'Yes', 'learn': 'Yes'}
{'name': 'Python', 'popular': 'Yes', 'learn': 'Yes'}   # no change in dictionary elements
Yes   # returned value from existing key-value pair

In first scenario, new key-value pair 'learn': 'Yes' added into the dictionary and new element value is returned. In second scenario, no change in dictionary elements and value from dictionary key is returned.

Using setdefault() to avoid errors

setdefault() method helps to avoid KeyError. If key does not exists in dictionary and we try to get that value using key index then we will get KeyError. But with setdefault() a new key-value pair with default value will be added into the dictionary. Even if default value is not given , then None will be considered as default value.

# setdefault default value is None
print("setdefault default value is None")
car_dict = {"brand": "Honda", "popular": "Yes"}
print(car_dict)
return_value = car_dict.setdefault("color")   # setdefault without default_value
print(car_dict)
print(return_value)

# Safely retrieving or setting a default value using setdefault()
user_settings = {}
returned_theme = user_settings.setdefault('theme', 'light')    # key does not exists
print(returned_theme)
print(user_settings)

In first scenario, default value if not given so None is considered as default value. In second scenario, key does not exists in dictionary, a new-value pair added into the dictionary.

Program Output

setdefault default value is None
{'brand': 'Honda', 'popular': 'Yes'}
{'brand': 'Honda', 'popular': 'Yes', 'color': None}
None
light
{'theme': 'light'}

Summary

In this article, we learned about fromkeys() and setdefault() built-in methods for dictionary. We learned about:

Code – Github Repository

All code snippets and programs for this article and for Python tutorial, can be accessed from Github repository – Comments and Docstring in Python.

Python Topics


Interview Questions & Answers

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *