Open In App

Python Dictionary fromkeys() Method

Last Updated : 09 Aug, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Python dictionary fromkeys() function returns the dictionary with key mapped and specific value. It creates a new dictionary from the given sequence with the specific value.

Python Dictionary fromkeys() Method Syntax:

Syntax : fromkeys(seq, val)

Parameters :

  • seq : The sequence to be transformed into a dictionary.
  • val : Initial values that need to be assigned to the generated keys. Defaults to None.

Returns : A dictionary with keys mapped to None if no value is provided, else to the value provided in the field. 

Python Dictionary fromkeys() Method Example:

Python3




seq = ('a', 'b', 'c')
print(dict.fromkeys(seq, None))


Output:

{'a': None, 'b': None, 'c': None}

Example 1: Demonstrating the working of fromkeys() 

Python3




seq = {'a', 'b', 'c', 'd', 'e'}
 
# creating dict with default values as None
res_dict = dict.fromkeys(seq)
 
print("The newly created dict with None values : " + str(res_dict))
 
# creating dict with default values as 1
res_dict2 = dict.fromkeys(seq, 1)
 
print("The newly created dict with 1 as value : " + str(res_dict2))


Output : 

The newly created dict with None values : {'d': None, 'a': None, 'b': None, 'c': None, 'e': None} 
The newly created dict with 1 as value : {'d': 1, 'a': 1, 'b': 1, 'c': 1, 'e': 1}

Behavior of Python Dictionary fromkeys() Method with Mutable objects as values, fromdict() can also be supplied with the mutable object as the default value. But in this case, a shallow copy is made of the dictionary, i.e. if we append a value in the original list, the append takes place in all the values of keys.

Prevention: Certain dictionary comprehension techniques can be used to create a new list of key values, that do not point to the original list of values of keys.

Example 2: Demonstrating the behavior with mutable objects

Python3




seq = {'a', 'b', 'c', 'd', 'e'}
lis1 = [2, 3]
 
res_dict = dict.fromkeys(seq, lis1)
 
# Printing created dict
print("The newly created dict with list values : "
      + str(res_dict))
 
# appending to lis1
lis1.append(4)
 
print("The dict with list values after appending : ", str(res_dict))
 
lis1 = [2, 3]
print('\n')
 
# using fromkeys() to convert sequence to dict
# using dict. comprehension
res_dict2 = {key: list(lis1) for key in seq}
 
# Printing created dict
print("The newly created dict with list values : "
      + str(res_dict2))
 
# appending to lis1
lis1.append(4)
 
# Printing dict after appending
# Notice that append doesnt take place now.
print("The dict with list values after appending (no change) : ", str(res_dict2))


Output:

The newly created dict with list values : {'d': [2, 3], 'e': [2, 3], 'c': [2, 3], 'a': [2, 3], 'b': [2, 3]} 
The dict with list values after appending : {'d': [2, 3, 4], 'e': [2, 3, 4], 'c': [2, 3, 4], 'a': [2, 3, 4], 'b': [2, 3, 4]}
The newly created dict with list values : {'d': [2, 3], 'e': [2, 3], 'c': [2, 3], 'a': [2, 3], 'b': [2, 3]} 
The dict with list values after appending (no change) : {'d': [2, 3], 'e': [2, 3], 'c': [2, 3], 'a': [2, 3], 'b': [2, 3]}

Example 3: Python Dictionary fromkeys() with an empty list

Python3




# Python3 code to demonstrate
# to initialize dictionary with list
# using fromkeys()
   
# using fromkeys() to construct
new_dict = dict.fromkeys(range(4), [])
       
# printing result
print ("New dictionary with empty lists as keys : " + str(new_dict))


Output:

New dictionary with empty lists as keys : {0: [], 1: [], 2: [], 3: []}


Previous Article
Next Article

Similar Reads

Python | Convert flattened dictionary into nested dictionary
Given a flattened dictionary, the task is to convert that dictionary into a nested dictionary where keys are needed to be split at '_' considering where nested dictionary will be started. Method #1: Using Naive Approach Step-by-step approach : Define a function named insert that takes two parameters, a dictionary (dct) and a list (lst). This functi
8 min read
Python | Convert nested dictionary into flattened dictionary
Given a nested dictionary, the task is to convert this dictionary into a flattened dictionary where the key is separated by '_' in case of the nested key to be started. Method #1: Using Naive Approach Step-by-step approach : The function checks if the input dd is a dictionary. If it is, then it iterates over each key-value pair in the dictionary, a
8 min read
Convert String Dictionary to Dictionary Python
Interconversions of data types have been discussed many times and have been quite a popular problem to solve. This article discusses yet another problem of interconversion of the dictionary, in string format to a dictionary. Let's discuss certain ways in which this can be done. Convert String Dictionary to Dictionary Using json.loads() This task ca
6 min read
Python | Dictionary initialization with common dictionary
Sometimes, while working with dictionaries, we might have an utility in which we need to initialize a dictionary with records values, so that they can be altered later. This kind of application can occur in cases of memoizations in general or competitive programming. Let’s discuss certain way in which this task can be performed. Method 1: Using zip
7 min read
Python - Update dictionary with other dictionary
Sometimes, while working with Python dictionaries, we can have problem in which we need to perform the update of dictionary with other keys of dictionary. This can have applications in domains in which we need to add certain records to previously captured records. Let's discuss certain ways in which this task can be performed. Method #1 : Using loo
9 min read
Convert Dictionary Value list to Dictionary List Python
Sometimes, while working with Python Dictionaries, we can have a problem in which we need to convert dictionary list to nested records dictionary taking each index of dictionary list value and flattening it. This kind of problem can have application in many domains. Let's discuss certain ways in which this task can be performed. Input : test_list =
9 min read
Python - Replace dictionary value from other dictionary
Given two dictionaries, update the values from other dictionary if key is present in other dictionary. Input : test_dict = {"Gfg" : 5, "is" : 8, "Best" : 10, "for" : 8, "Geeks" : 9}, updict = {"Geeks" : 10, "Best" : 17} Output : {'Gfg': 5, 'is': 8, 'Best': 17, 'for': 8, 'Geeks': 10} Explanation : "Geeks" and "Best" values updated to 10 and 17. Inpu
6 min read
Python - Append Dictionary Keys and Values ( In order ) in dictionary
Given a dictionary, perform append of keys followed by values in list. Input : test_dict = {"Gfg" : 1, "is" : 2, "Best" : 3} Output : ['Gfg', 'is', 'Best', 1, 2, 3] Explanation : All the keys before all the values in list. Input : test_dict = {"Gfg" : 1, "Best" : 3} Output : ['Gfg', 'Best', 1, 3] Explanation : All the keys before all the values in
5 min read
Python - Combine two dictionaries having key of the first dictionary and value of the second dictionary
Given two dictionaries. The task is to merge them in such a way that the resulting dictionary contains the key from the first dictionary and the value from the second dictionary. Examples: Input : test_dict1 = {"Gfg" : 20, "is" : 36, "best" : 100}, test_dict2 = {"Gfg2" : 26, "is2" : 20, "best2" : 70} Output : {'Gfg': 26, 'is': 20, 'best': 70} Expla
8 min read
Python program to update a dictionary with the values from a dictionary list
Given a dictionary and dictionary list, update the dictionary with dictionary list values. Input : test_dict = {"Gfg" : 2, "is" : 1, "Best" : 3}, dict_list = [{'for' : 3, 'all' : 7}, {'and' : 1, 'CS' : 9}] Output : {'Gfg': 2, 'is': 1, 'Best': 3, 'for': 3, 'all': 7, 'and': 1, 'CS': 9} Explanation : All dictionary keys updated in single dictionary. I
8 min read