VOOZH about

URL: https://www.geeksforgeeks.org/python/python-dictionary-fromkeys-method/

⇱ Python Dictionary fromkeys() Method - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Python Dictionary fromkeys() Method

Last Updated : 9 Aug, 2022

Python dictionary fromkeys() function returns the dictionary with key mapped and specific value. It creates a new dictionary from the given sequence with the specific value.

Python Dictionary fromkeys() Method Syntax:

Syntax : fromkeys(seq, val)

Parameters :

  • seq : The sequence to be transformed into a dictionary.
  • val : Initial values that need to be assigned to the generated keys. Defaults to None.

Returns : A dictionary with keys mapped to None if no value is provided, else to the value provided in the field. 

Python Dictionary fromkeys() Method Example:

Output:

{'a': None, 'b': None, 'c': None}

Example 1: Demonstrating the working of fromkeys() 

Output : 

The newly created dict with None values : {'d': None, 'a': None, 'b': None, 'c': None, 'e': None} 
The newly created dict with 1 as value : {'d': 1, 'a': 1, 'b': 1, 'c': 1, 'e': 1}

Behavior of Python Dictionary fromkeys() Method with Mutable objects as values, fromdict() can also be supplied with the mutable object as the default value. But in this case, a shallow copy is made of the dictionary, i.e. if we append a value in the original list, the append takes place in all the values of keys.

Prevention: Certain dictionary comprehension techniques can be used to create a new list of key values, that do not point to the original list of values of keys.

Example 2: Demonstrating the behavior with mutable objects

Output:

The newly created dict with list values : {'d': [2, 3], 'e': [2, 3], 'c': [2, 3], 'a': [2, 3], 'b': [2, 3]} 
The dict with list values after appending : {'d': [2, 3, 4], 'e': [2, 3, 4], 'c': [2, 3, 4], 'a': [2, 3, 4], 'b': [2, 3, 4]}
The newly created dict with list values : {'d': [2, 3], 'e': [2, 3], 'c': [2, 3], 'a': [2, 3], 'b': [2, 3]} 
The dict with list values after appending (no change) : {'d': [2, 3], 'e': [2, 3], 'c': [2, 3], 'a': [2, 3], 'b': [2, 3]}

Example 3: Python Dictionary fromkeys() with an empty list

Output:

New dictionary with empty lists as keys : {0: [], 1: [], 2: [], 3: []}
Comment
Article Tags: