Python Dictionary fromkeys()

The fromkeys() method creates a dictionary from the given sequence of keys and values.

Example


fromkeys() Syntax

The syntax of the fromkeys() method is:

dict.fromkeys(alphabets,number)

Here, alphabets and numbers are the key and value of the dictionary.


fromkeys() Parameters

The fromkeys() method can take two parameters:

  • alphabets - are the keys that can be any iterables like string, set, list, etc.
  • numbers (Optional) - are the values that can be of any type or any iterables like string, set, list, etc.

Note: The same value is assigned to all the keys of the dictionary.


fromkeys() Return Value

The fromkeys() method returns:

  • a new dictionary with the given sequence of keys and values

Note: If the value of the dictionary is not provided, None is assigned to the keys.


Example 1: Python Dictionary fromkeys() with Key and Value

Output

{'a': 'vowel', 'u': 'vowel', 'e': 'vowel', 'i': 'vowel', 'o': 'vowel'}

In the above example, we have used the fromkeys() method to create the dictionary with the given set of keys and string value.

Here, the fromkeys() method creates a new dictionary named vowels from keys and value. All the keys of the dictionary are assigned with the same value.


Example 2: fromkeys() without Value

Output

{1: None, 2: None, 4: None}

In the above example, we have created a dictionary named numbers with the given list of keys.

We have not provided any values, so all the keys are assigned None by default.


Example 3: fromkeys() To Create A Dictionary From Mutable Object

Output

{'a': [1], 'u': [1], 'o': [1], 'e': [1], 'i': [1]}
{'a': [1, 2], 'u': [1, 2], 'o': [1, 2], 'e': [1, 2], 'i': [1, 2]}

In the above example, we have used a list as the value for the dictionary. The iterables like list, dictionary, etc are the mutable objects, meaning they can be modified.

Here, when we update the list value using append, the keys are assigned with the new updated values. This is because each element is pointing to the same address in the memory.

To solve this problem, we can use dictionary comprehension.


Dictionary comprehension for mutable objects

We can use dictionary comprehension and prevent updating the dictionary when the mutable object (list, dictionary, etc) is updated. For example,

Output

{'a': [1], 'u': [1], 'o': [1], 'e': [1], 'i': [1]}
{'a': [1], 'u': [1], 'o': [1], 'e': [1], 'i': [1]}

In the above example, we have used dictionary comprehension to create a dictionary named vowels.

Here, the value is not assigned to the keys of the dictionary. But, for each key in keys, a new list of value is created. The newly created list is assigned each key in the dictionary.


Recommended Reading: Python Dictionary Comprehension.