Python Tutorial Python Advanced Python References Python Libraries

Python Dictionary - fromkeys() Method



The Python fromkeys() method is used to create a dictionary with keys specified in an iterable. An iterable object can be any data structure like list, tuple, set, string, dictionary and range iterable.

Syntax

dict.fromkeys(keys_iter, val)

Parameters

keys_iter Required. iterable object like list, tuple, set, string , dictionary and range() etc containing keys of the dictionary.
val Optional. value for all keys. Default value of this parameter is None.

Return Value

Returns a dictionary with keys specified in an iterable.

Example: using list, tuple, set, string and range iterable

In the example below, different iterators are used with fromkeys() method to create a dictionary.

#using list iterable
MyList = ['name', 'age']
MyDict = dict.fromkeys(MyList)
print(MyDict)

#using tuple iterable
MyTuple = ('name', 'age')
MyDict = dict.fromkeys(MyTuple, 'Missing')
print(MyDict)

#using set iterable
MySet = {'name', 'age'}
MyDict = dict.fromkeys(MySet, 'Blank')
print(MyDict)

print()
#using range iterable
MyDict = dict.fromkeys(range(1,4))
print(MyDict)

#using string iterable
MyDict = dict.fromkeys('123')
print(MyDict)

The output of the above code will be:

{'name': None, 'age': None}
{'name': 'Missing', 'age': 'Missing'}
{'name': 'Blank', 'age': 'Blank'}

{1: None, 2: None, 3: None}
{'1': None, '2': None, '3': None}

Example: using dictionary iterable

In the example below, dictionary is used to create another dictionary.

OldDict = {
  'name': 'John',
  'age': 25
}
MyDict = dict.fromkeys(OldDict)
print(MyDict)

MyDict = dict.fromkeys(OldDict.keys())
print(MyDict)

MyDict = dict.fromkeys(OldDict.values())
print(MyDict)

The output of the above code will be:

{'name': None, 'age': None}
{'name': None, 'age': None}
{'John': None, 25: None}

❮ Python Dictionary Methods