Python Dictionary fromkeys() method
The dictionary.fromkeys() method in Python creates a new dictionary from the given sequence of elements and returns a dictionary with the specified keys and values.
Syntax
1 2 3 |
dictionary.fromkeys(sequence[, value]) |
Parameter
sequence- This parameter represents the sequence of elements which is to be used as keys for the new dictionary.
value(optional)- This argument signifies the value which is set for each element of the dictionary.
Return
This method returns a dictionary with the specified keys and values.
Example 1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
# Python program explaining # the dictionary.fromkeys() method dictionary={"banana": "apple", "orange": "mango", "grapes": 5 } # initializing the sequence sequence = ('Monday', 'Tuesday', 'Wednesday') # initializing the key key = 1 # creating a new dictionary from the given sequence of elements dict = dictionary.fromkeys(sequence, key) # returning a dictionary with the specified keys and values. print(dict) |
Output
1 2 3 |
{'Tuesday': 1, 'Monday': 1, 'Wednesday': 1} |
Example 2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
# Python program explaining # the dictionary.fromkeys() method # initializing sequence vowels = { 'a', 'e', 'i', 'o', 'u' } # using fromkeys() to convert sequence to dict # initializing with None dictionary = dict.fromkeys(vowels) # Printing created dict print ("The newly created dict with no values = " + str(dictionary)) # using fromkeys() to convert vowels to dict # initializing with 9 dictionary2 = dict.fromkeys(vowels, 9) # Printing the dict print ("New created dict with 9 as its value = " + str(dictionary2)) |
Output
1 2 3 4 |
The newly created dict with no values = {'e': None, 'i': None, 'u': None, 'o': None, 'a': None} New created dict with 9 as its value = {'e': 9, 'i': 9, 'u': 9, 'o': 9, 'a': 9} |