Tutorial Study Image

Python fromkeys()

The fromkeys() function in python helps to create a new dictionary using the given sequence with given values.


dictionary.fromkeys(sequence[, value]) #where sequence may be a integers, string etc
 

fromkeys() Parameters:

Takes two parameters. In case if we create a dictionary from a mutable(value can be changed) object list and later the mutable object is changed then it will reflect each of the elements in the sequence. This is because each element is pointed to the same object in the memory. To avoid this problem,  dictionary comprehension is used.

Parameter Description Required / Optional
sequence sequence of elements which is to be used as keys for the new dictionary Required
value  value which is set to each each element of the dictionary.Default value is None Optional

fromkeys() Return Value

If the value argument is given, each element of the newly created dictionary is assigned with the provided value.

Input Return Value
If parameters new dictionary

Examples of fromkeys() method in Python

Example 1: How to create a dictionary from a sequence of keys


# vowels keys
keylist = {'a', 'e', 'i', 'o', 'u' }

vowelslist = dict.fromkeys(keylist)
print(vowelslist)
 

Output:


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

Example 2: How to create a dictionary from a sequence of keys with value


# vowels keys
keylist = {'a', 'e', 'i', 'o', 'u' }
value = 'vowel'

vowelslist = dict.fromkeys(keylist, value)
print(vowelslist)
 

Output:


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

Example 3: How to create a dictionary from mutable object list


# vowels keys
keylist = {'a', 'e', 'i', 'o', 'u' }
value = [4]

vowelslist = dict.fromkeys(keylist, value)
print(vowelslist)

# updating the value
value.append(5)
print(vowelslist)
 

Output:


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