Creating a dictionary from a list with default values allows us to map each item in the list to a specific default value. Using dict.fromkeys(), we can quickly create a dictionary where all the keys from the list are assigned a default value, such as None or any other constant.
Using dict.fromkeys()
This method creates a dictionary where each key from the list is associated with a default value.
k = ['a', 'b', 'c', 'd']
d = 0
# Create dictionary with default values
res = dict.fromkeys(k, d)
print(res)
Output
{'a': 0, 'b': 0, 'c': 0, 'd': 0}
Explanation
- The
fromkeys()method creates a dictionary using the provided list of keys and assigns each key the default value passed.
Using Dictionary Comprehension
Dictionary Comprehension gives more control over how the keys are mapped to values.
keys = ['a', 'b', 'c', 'd']
d = 0
# Create dictionary with default values using comprehension
result = {key: d for key in keys}
print(result)
Output
{'a': 0, 'b': 0, 'c': 0, 'd': 0}
Explanation: A dictionary comprehension loops through the keys list and assigns each key the default_value.
Using a for loop
You can manually iterate through the list and add each element to the dictionary with the default value.
keys = ['a', 'b', 'c', 'd']
d = 0
# Create dictionary with default values using a for loop
res = {}
for key in keys:
res[key] = d
print(res)
Output
{'a': 0, 'b': 0, 'c': 0, 'd': 0}
Explanation: for loop iterates over the keys list and assigns the default value to each key in the dictionary.