Sometimes it becomes necessary to form a dictionary from the given keys. Roughly doing this would take time and be more tedious work. Hence, fromkeys () helps us to easily solve this problem using just one method. This article explains the operational and other aspects associated with this feature.
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.
Code # 1: Demonstration of fromkeys ()
|
Exit :
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}
The fromdict () behavior with mutable objects as values:
The fromdict () function can also be supplied with a multilatable object as a s default values. But in this case, a deep copy is created from the dictionary, that is, if we add a value to the original list, the addition occurs in all key values.
Prevention: Certain dictionary comprehension techniques can be used to creating a new list as key values that does not point to the original list as key values.
Code # 2: Demonstrate 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]}