Open In App

Python Create Dictionary from List with Default Values

Last Updated : 12 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Dictionaries in Python are versatile data structures that allow you to store and retrieve key-value pairs efficiently. Sometimes, you may need to initialize a dictionary with default values based on a list of keys. In this article, we’ll explore some simple and commonly used methods to create a dictionary from a list with default values in Python.

Python Create Dictionary from List with Default Values

Below, are the methods of Python Create Dictionary from List with Default Values.

Python Create Dictionary from List with Default Values Using For Loop

In this example, the below code initializes a dictionary `result_dict` with keys from the list `keys` and sets each key’s value to the `default_value` (0). Finally, it prints the resulting dictionary.

Python3




keys = ['apple', 'banana', 'cherry']
default_value = 0
 
result_dict = {}
for key in keys:
    result_dict[key] = default_value
 
print(result_dict)


Output

{'apple': 0, 'banana': 0, 'cherry': 0}

Python Create Dictionary from List with Default Values Using dict.fromkeys() Method

In this example, below code creates a dictionary `result_dict` with keys from the list `keys`, and each key is assigned the `default_value` (0) using the `dict.fromkeys()` method. The resulting dictionary is then printed.

Python3




keys = ['apple', 'banana', 'cherry']
default_value = 0
 
result_dict = dict.fromkeys(keys, default_value)
print(result_dict)


Output

{'apple': 0, 'banana': 0, 'cherry': 0}

Python Create Dictionary from List with Default Values Using Dictionary Comprehension

In this example, below code utilizes a dictionary comprehension to create a dictionary `result_dict` with keys from the list `keys`, and each key is assigned the `default_value` (0). The resulting dictionary is then printed.

Python3




keys = ['apple', 'banana', 'cherry']
default_value = 0
 
result_dict = {key: default_value for key in keys}
print(result_dict)


Output

{'apple': 0, 'banana': 0, 'cherry': 0}

Python Create Dictionary from List with Default Values Using zip() Function

In this example, below code uses the `zip()` function to combine the list of keys (`keys`) with a list containing the `default_value` (0) repeated for each key. The resulting pairs are then used to create a dictionary named `result_dict`, which is printed afterward.

Python3




keys = ['apple', 'banana', 'cherry']
default_value = 0
 
result_dict = dict(zip(keys, [default_value] * len(keys)))
print(result_dict)


Output

{'apple': 0, 'banana': 0, 'cherry': 0}


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads