Facebook Page Twitter Page LinkedIn Page
× Python Tutorial Python Advanced Python Resources Python Libraries


The dictionary 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 and dictionary etc. The range() function can also be used as an iterable if numeric keys are required in the dictionary.

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() as iterable

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

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

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

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

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

#using string as an 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 as iterable

In the below example, dictionary is used as an iterable to create a 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




5