Python Dictionary fromkeys():

The fromkeys() method creates a new dictionary with keys from a given sequence and values set to a given value in Python.

Method signature

The signature for the fromkeys() method is as shown below. Here, d is a new dictionary created from the sequence and value passed as a parameter. We will store the sequence as a key and the corresponding value as v. Just because this is a class method, we call it from dict class.

d=dict.fromkeys(sequence,v)

Method parameters and return type

  • The fromkeys() method takes two parameters. Here, the first parameter is a sequence to store as dictionary keys. Furthermore, the second parameter is a value for the generated keys. However, in the absence of values, it maps keys with none.
  • However, it returns the dictionary with the keys and the values.

Python Dictionary fromkeys Examples:

Example 1: In this example, let us take a set containing a serial number referred as “srno”. Here, we store a string in the variable “dept”. In this case, all keys will have the same value computer.

#Initializing 
srno={1,2,3,4,5}
dept="Computer"
# Using fromkeys
d=dict.fromkeys(srno,dept)
#Printing 
print("Dictionary Created ",d)

Output

Dictionary created {1: 'Computer', 2: 'Computer', 3: 'Computer', 4: 'Computer', 5: 'Computer'}

Example 2:

In this case, We will now take a set of numbers called “n”. Since a second parameter is absent, the value “None” is stored for each key.

#Initializing 
n={1,2,3,4,5}
# Using fromkeys method
d=dict.fromkeys(n)
#Printing 
print("Dictionary is ",d)

Output

Dictionary is  {1: None, 2: None, 3: None, 4: None, 5: None}

Example 3:

In this example, We will demonstrate how the method will behave if the value provided is a list data structure. As a result, each key will be assigned all the values in the list.

#Initializing 
n={1,2,3,4,5}
l=["Mumbai","Delhi"]
# Using fromkeys method
d=dict.fromkeys(n,l)
#Printing 
print("Dictionary is ",d)

Output

Dictionary is  {1: ['Mumbai', 'Delhi'], 2: ['Mumbai', 'Delhi'], 3: ['Mumbai', 'Delhi'], 4: ['Mumbai', 'Delhi'], 5: ['Mumbai', 'Delhi']}

Conclusion

The fromkeys() method is a class method, so it’s always called dict. Hence, this method creates the new dictionary taking the sequence as a key and its values.

References

Happy Learning 🙂