Python dictionary fromKeys() method is used to create a new dictionary with specified keys and a uniform specified value for all the keys.
Syntax
dictionary.fromkeys(keys, value)
Parameters
- keys: It is an iterable specifying the keys of the new dictionary.
- value: The value is for all keys. The default value is None.
Return value
This method returns a new dictionary with a given sequence of elements as the dictionary’s keys.
Visual Representation
Example 1: Using Specified Value
StarWars = ('Luke', 'Vader', 'Ray', 'Yoda')
StarTrek = ('Spock')
universe = dict.fromkeys(StarWars, StarTrek)
print(universe)
Output
{'Luke': 'Spock', 'Vader': 'Spock', 'Ray': 'Spock', 'Yoda': 'Spock'}
Above output shows that each key in StarWars is associated with the same tuple (‘Spock’) as its value.
Example 2: Using Default Value
StarWars = ('Luke', 'Vader', 'Ray', 'Yoda')
universe = dict.fromkeys(StarWars)
print(universe)
Output
{'Luke': None, 'Vader': None, 'Ray': None, 'Yoda': None}
In the above example, since no values were provided, all the keys are assigned None by default.
Example 3: Create A dictionary from Mutable Object
# set of data
alphabet = {'a', 'b', 'c', 'd', 'e'}
value = [5]
data = dict.fromkeys(keys, value)
print(data)
value.append(10)
print(data)
Output
{'a': [5], 'd': [5], 'c': [5], 'e': [5], 'b': [5]}
{'a': [5, 10], 'd': [5, 10], 'c': [5, 10], 'e': [5, 10], 'b': [5, 10]}
In this example, When we update the list value by appending an element, the values associated with each key also reflect this change because they all reference the same list in memory. Iterables like lists and dictionaries are mutable objects, which means they can be modified after creation.
Example 4: Dictionary comprehension for mutable objects
# set of data
keys = {'a', 'b', 'c', 'd', 'e'}
value = [5]
data = {key: list(value) for key in keys}
print(data)
value.append(10)
print(data)
Output
{'c': [5], 'e': [5], 'a': [5], 'd': [5], 'b': [5]}
{'c': [5], 'e': [5], 'a': [5], 'd': [5], 'b': [5]}
That’s it.
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.