Python | Initialize list with empty dictionaries
While working with Python, we can have a problem in which we need to initialize a list of a particular size with empty dictionaries. This task has it’s utility in web development to store records. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using {} + "*" operator
This task can be performed using the “*” operator. We can create a list containing single empty dictionary and then multiply it by Number that is size of list. The drawback is that similar reference dictionaries will be made which will point to similar memory location.
# Python3 code to demonstrate working of # Initialize list with empty dictionaries # using {} + "*" operator # Initialize list with empty dictionaries # using {} + "*" operator res = [{}] * 6 print("The list of empty dictionaries is : " + str(res)) |
The list of empty dictionaries is : [{}, {}, {}, {}, {}, {}]
Method #2 : Using {} + list comprehension
This is perhaps the better and correct way to perform this task. We initialize the each index of list with dictionary, this way, we have independently referring dictionaries and don’t point to single reference.
# Python3 code to demonstrate working of # Initialize list with empty dictionaries # using {} + list comprehension # Initialize list with empty dictionaries # using {} + "*" operator res = [{} for sub in range(6)] print("The list of empty dictionaries is : " + str(res)) |
The list of empty dictionaries is : [{}, {}, {}, {}, {}, {}]
Recommended Posts:
- Python | Sum list of dictionaries with same key
- Python | Merging two list of dictionaries
- Python | Set Difference in list of dictionaries
- Python | Flatten given list of dictionaries
- Python | Get values of particular key in list of dictionaries
- Python | Segregating key's value in list of dictionaries
- Python | Ways to initialize list with alphabets
- Python | Initialize a dictionary with only keys from a list
- Python | Sort given list of dictionaries by date
- Python | Removing dictionary from list of dictionaries
- Python | Split dictionary of lists to list of dictionaries
- Ways to sort list of dictionaries by values in Python – Using itemgetter
- Ways to sort list of dictionaries by values in Python - Using lambda function
- Python | Check whether a list is empty or not
- Python | First Non-Empty String in list
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



