Python Dictionary fromkeys()
The dict.fromkeys()
method creates a new dictionary from the given iterable (string, list, set, tuple) as keys and with the specified value.
Syntax:
dictionary.fromkeys(sequence, value)
Parameters:
- sequence: Required. A sequence/iterable, whose elements would be set as keys of the new dictionary.
- value: Optional. A value of each key. Defaults to None.
Return Value:
Returns a new dictionary.
The following creates a new dict object using the dict.fromkeys()
method.
keys = {'Mumbai','Bangalore','Chicago','New York'}
value = 'city'
dictionary = dict.fromkeys(keys, value)
print(dictionary)
{'Mumbai': 'city', 'New York': 'city', 'Bangalore': 'city', 'Chicago': 'city'}
If the value parameter is not passed, the values of the dictionary will be None.
keys = {'Mumbai','Bangalore','Chicago','New York'}
dictionary = dict.fromkeys(keys)
print(dictionary)
{'Mumbai': None, 'New York': None, 'Bangalore': None, 'Chicago': None}
The keys
parameter can be any iterable type such as string, list, set, or tuple.
chDict = dict.fromkeys('Hello','char') # string to dict
print(chDict)
nums = (1, 2, 3, 4, 5) # tuple to dict
val = 'Numbers'
numDict = dict.fromkeys(nums, val)
print(numDict)
{'H': 'char', 'e': 'char', 'l': 'char', 'o': 'char'}
{1: 'Numbers', 2: 'Numbers', 3: 'Numbers', 4: 'Numbers', 5: 'Numbers'}