In this tutorial, we’ll learn how to use Python dict fromkeys() method step by step using proper code examples.
What is Python Dict fromkeys() Method?
This method create a new dictionary using a given sequence of keys and values. It returns the newly created dictionary.
Syntax of fromkeys()
dictionaryName.fromkeys(key,value)
It takes two arguments. First one is specified for keys of Python dictionary and second one for values. You can use items like string, list, set etc. in both these two arguments.
Example 1: Create a Dictionary Using Sequence of Items
items={'name','age','weight'} value=24 newDictionary=dict.fromkeys(items,value) print(newDictionary)
Output
{'weight': 24, 'name': 24, 'age': 24}
All the items are fetched from set. As we’ve passed only a single value to the second argument of Python dictionary fromkeys() method, so the same value will be assigned to each key. The order of items(key, value pairs) are random.
Example 2: Passing only Key to fromkeys() Method
items={'name','age','weight'} newDictionary=dict.fromkeys(items) // only key is specified print(newDictionary)
Output
{'name': None, 'age': None, 'weight': None}
If the value is not specified then None is assigned to each key in dictionary.
Example 3: Using Mutable Object To Create Dictionary
items={'a','b','c'} value=[35] newDictionary=dict.fromkeys(items,value) print(newDictionary) value.append('green') print(newDictionary)
Output
{'c': [35], 'b': [35], 'a': [35]} {'c': [35, 'green'], 'b': [35, 'green'], 'a': [35, 'green']}
We’ve used a Python list as a value to this Python dict fromkeys() method.
As you can see in the above code, we’ve used the append method to add an item to the list after the fromkeys() statement and the updated list is assigned to the new dictionary created using Python dict fromkeys() method.
Reason is that in memory, each element is pointing to the same address. Let’s see how to solve this.
Example 4: Using Dictionary Comprehension for Mutable Object
Let’s see how to make use of the dictionary comprehension to prevent the dictionary from updating whenever some update occurs to the mutable object(dictionary, list etc.). See below code:
items={'a','b','c'} value=[35] newDictionary={key:list(value) for key in items} print(newDictionary) value.append('green') print(newDictionary)
Output
{'a': [35], 'b': [35], 'c': [35]} // before updating list {'a': [35], 'b': [35], 'c': [35]} // after updating list
For each key in items, a new list of value is created and its assigned to each key in dictionary. As you can see here, now the dictionary is not updating when we add some items to the list.
Conclusion
To conclude, hope you now have a good practical understanding of how to use Python dict fromkeys() method. Do share your valuable feedback with us. Thank you for reading this post.