![]() |
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 ValuesBelow, are the methods of Python Create Dictionary from List with Default Values.
Python Create Dictionary from List with Default Values Using For LoopIn 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
Output
{'apple': 0, 'banana': 0, 'cherry': 0} Python Create Dictionary from List with Default Values Using
|
keys = [ 'apple' , 'banana' , 'cherry' ] default_value = 0 result_dict = dict .fromkeys(keys, default_value) print (result_dict) |
{'apple': 0, 'banana': 0, 'cherry': 0}
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.
keys = [ 'apple' , 'banana' , 'cherry' ] default_value = 0 result_dict = {key: default_value for key in keys} print (result_dict) |
{'apple': 0, 'banana': 0, 'cherry': 0}
zip()
FunctionIn 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.
keys = [ 'apple' , 'banana' , 'cherry' ] default_value = 0 result_dict = dict ( zip (keys, [default_value] * len (keys))) print (result_dict) |
{'apple': 0, 'banana': 0, 'cherry': 0}
Reffered: https://www.geeksforgeeks.org
Python |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 13 |