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:

  1. sequence: Required. A sequence/iterable, whose elements would be set as keys of the new dictionary.
  2. 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.

Example:
keys = {'Mumbai','Bangalore','Chicago','New York'}
value = 'city'
dictionary = dict.fromkeys(keys, value)
print(dictionary)
Output
{'Mumbai': 'city', 'New York': 'city', 'Bangalore': 'city', 'Chicago': 'city'}

If the value parameter is not passed, the values of the dictionary will be None.

Example:
keys = {'Mumbai','Bangalore','Chicago','New York'}
dictionary = dict.fromkeys(keys)
print(dictionary)
Output
{'Mumbai': None, 'New York': None, 'Bangalore': None, 'Chicago': None}

The keys parameter can be any iterable type such as string, list, set, or tuple.

Example:
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)
Output
{'H': 'char', 'e': 'char', 'l': 'char', 'o': 'char'} 
{1: 'Numbers', 2: 'Numbers', 3: 'Numbers', 4: 'Numbers', 5: 'Numbers'}
Want to check how much you know Python?