Python Dictionary fromkeys() Method
Last Updated :
09 Aug, 2022
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' }
res_dict = dict .fromkeys(seq)
print ( "The newly created dict with None values : " + str (res_dict))
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)
print ( "The newly created dict with list values : "
+ str (res_dict))
lis1.append( 4 )
print ( "The dict with list values after appending : " , str (res_dict))
lis1 = [ 2 , 3 ]
print ( '\n' )
res_dict2 = {key: list (lis1) for key in seq}
print ( "The newly created dict with list values : "
+ str (res_dict2))
lis1.append( 4 )
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
new_dict = dict .fromkeys( range ( 4 ), [])
print ( "New dictionary with empty lists as keys : " + str (new_dict))
|
Output:
New dictionary with empty lists as keys : {0: [], 1: [], 2: [], 3: []}
Similar Reads
Python Dictionary Methods
Python dictionary methods is collection of Python functions that operates on Dictionary. Python Dictionary is like a map that is used to store data in the form of a key: value pair. Python provides various built-in functions to deal with dictionaries. In this article, we will see a list of all the f
5 min read
Python Dictionary clear()
clear() method in Python is used to remove all items (key-value pairs) from a dictionary. After calling this method, the dictionary will become empty and its length will be 0. This method is part of the built-in dictionary operations in Python. Example: [GFGTABS] Python d = {1: "geeks", 2:
2 min read
Python Dictionary copy()
Python Dictionary copy() method returns a shallow copy of the dictionary. let's see the Python Dictionary copy() method with examples: Examples Input: original = {1:'geeks', 2:'for'} new = original.copy() // Operation Output: original: {1: 'one', 2: 'two'} new: {1: 'one', 2: 'two'}Syntax of copy() m
3 min read
Python Dictionary fromkeys() Method
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
3 min read
Python Dictionary get() Method
Python Dictionary get() Method returns the value for the given key if present in the dictionary. If not, then it will return None (if get() is used with only one argument). Python Dictionary get() Method Syntax:Syntax : Dict.get(key, Value) Parameters: key: The key name of the item you want to retur
4 min read
Python Dictionary items() method
items() method in Python returns a view object that contains all the key-value pairs in a dictionary as tuples. This view object updates dynamically if the dictionary is modified. Example: [GFGTABS] Python d = {'A': 'Python', 'B': 'Java', 'C': 'C++'} #
2 min read
Python Dictionary keys() method
keys() method in Python dictionary returns a view object that displays a list of all the keys in the dictionary. This view is dynamic, meaning it reflects any changes made to the dictionary (like adding or removing keys) after calling the method. Example: [GFGTABS] Python d = {'A': 'Geek
2 min read
Python Dictionary pop() Method
Python dictionary pop() method removes and returns the specified element from the dictionary. Example: C/C++ Code # inializing dictionary student student = {"rahul":7, "Aditya":1, "Shubham":4} # priting original dictionary print(student) # using dictionary pop suspended
4 min read
Python Dictionary popitem() method
popitem() method in Python is used to remove and return the last key-value pair from the dictionary. It is often used when we want to remove a random element, particularly when the dictionary is not ordered. Example: [GFGTABS] Python d = {1: '001', 2: '010', 3: '011'} # Using
2 min read
Python Dictionary setdefault() Method
Python Dictionary setdefault() returns the value of a key (if the key is in dictionary). Else, it inserts a key with the default value to the dictionary. Python Dictionary setdefault() Method Syntax: Syntax: dict.setdefault(key, default_value)Parameters: It takes two parameters: key - Key to be sear
2 min read