Home »
Python
Python Dictionary fromkeys() Method (with Examples)
By IncludeHelp Last updated : December 21, 2024
In this tutorial, we will learn about the fromkeys() method of a dictionary with its usage, syntax, parameters, return type, and examples.
Python Dictionary fromkeys() Method
The fromkeys() is an inbuilt method of dict class that is used to create a dictionary with the given keys and value (The value for all keys). The method is called with the class name (dict) and returns a newly created dictionary.
Syntax
The following is the syntax of fromkeys() method:
dict.fromkeys(keys, value)
Parameter(s):
The following are the parameter(s):
- keys – It represents a container (iterable) with keys.
- value – It is an optional parameter, that is used to specify the value. The default value of None.
Return Value
The return type of this method is <class 'dict'>, it returns the newly created dictionary with specified keys and values.
Example 1: Use of Dictionary fromkeys() Method
# keys iterbale
keys = ('id', 'age', 'perc')
# value
value = 0
# creating dictionary with keys and value
x = dict.fromkeys(keys, value)
# printing dictionary
print("data of x dictionary...")
print(x)
# creating dictionary with keys only
y = dict.fromkeys(keys)
# printing dictionary
print("data of y dictionary...")
print(y)
Output
data of x dictionary...
{'perc': 0, 'id': 0, 'age': 0}
data of y dictionary...
{'perc': None, 'id': None, 'age': None}
Example 2: Use of Dictionary fromkeys() Method
# keys iterbale
keys = ("a", "b", "c", "d", "c")
# creating dictionary with keys and
# value as 10
x = dict.fromkeys(keys, 10)
# printing dictionary and its type
print("Dictionary (x)...")
print(x)
print("Types of Dictionary (x)...")
print(type(x))
Output
Dictionary (x)...
{'a': 10, 'b': 10, 'c': 10, 'd': 10}
Types of Dictionary (x)...
<class 'dict'>