Python – Custom dictionary initialization in list

While working with Python, we can have a problem in which we need to initialize a list of a particular size with custom 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 {dict} + "*" operator
This task can be performed using the “*” operator. We can create a list containing single custom 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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Custom dictionary initialization in list
# using {dict} + "*" operator
  
# Initialize dict 
test_dict = {'gfg' : 1, 'is' : 2, 'best' : 3}
  
# Custom dictionary initialization in list
# using {dict} + "*" operator
res = [test_dict] * 6
  
print("The list of custom dictionaries is : " + str(res))

chevron_right


Output :



The list of custom dictionaries is : [{'gfg': 1, 'best': 3, 'is': 2}, {'gfg': 1, 'best': 3, 'is': 2}, {'gfg': 1, 'best': 3, 'is': 2}, {'gfg': 1, 'best': 3, 'is': 2}, {'gfg': 1, 'best': 3, 'is': 2}, {'gfg': 1, 'best': 3, 'is': 2}]

 

Method #2 : Using {dict} + 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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Custom dictionary initialization in list
# using {dict} + list comprehension
  
# Initialize dict 
test_dict = {'gfg' : 1, 'is' : 2, 'best' : 3}
  
# Custom dictionary initialization in list
# using {dict} + list comprehension
res = [test_dict for sub in range(6)]
  
print("The list of custom dictionaries is : " + str(res))

chevron_right


Output :

The list of custom dictionaries is : [{'gfg': 1, 'best': 3, 'is': 2}, {'gfg': 1, 'best': 3, 'is': 2}, {'gfg': 1, 'best': 3, 'is': 2}, {'gfg': 1, 'best': 3, 'is': 2}, {'gfg': 1, 'best': 3, 'is': 2}, {'gfg': 1, 'best': 3, 'is': 2}]


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

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.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.