In this section we will learn what the Dictionary fromkeys() method is and how to use it in Python.
What is Dictionary fromkeys() Method in Python?
The Python Dictionary fromkeys() method is used to create a dictionary from the items of an iterable object.
Basically, this method takes the items of an iterable object (for example a tuple or a list) and sets them as the keys of the new dictionary.
By default, these items will have the value None, but then this method takes another argument that could be anything and it will be used as the default value for the entire keys of the dictionary.
Python Dictionary fromkeys() Method Syntax:
dictionary.fromkeys(iterable, defaultValue)
Dictionary fromkeys() Method Parameter:
The method takes two arguments:
- The first argument is an iterable object that we want to take its items and set as the keys for the new dictionary.
- The second argument, which is optional, is a default value that will be assigned to each key of the new dictionary. This value, as mentioned before, is optional and if ignored, the value None will be set for those keys.
Dictionary fromkeys() Method Return Value
The return value of this method is a new dictionary.
Example: using python dictionary fromkeys() method
list = ["name","lastName","age"] dictionary = dict.fromkeys(list,"unknown") print(dictionary)
Output:
{'name': 'unknown', 'lastName': 'unknown', 'age': 'unknown'}