Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Adding a dictionary into a dictionary in a for loop with update()

I’m trying to add a temporary dictionary that gets generated every iteration in a for loop into a final dictionary. The aim of this final dictionary is to summurize every temporary dictionary that was generated in the loop. The keys of the temporary dictionary are numbers generated randomly, and the values are lists of random numbers too.
While searching on forums to find how to do this, I often came across the update() function, meant to work as follows : final_dictionary.udpate(temporary_dictionary).
However, I’m encountering a problem with this function. Here’s my code :

import random
final_dictionary = {}
for i in range(30):
     rd_key = random.randint(1, 10)
     rd_value = [random.randint(1, 10) for i in range(0, 10)]
     temp_dictionary = {rd_key: rd_value}
     final_dictionary.update(temp_dictionary)

What I want from this loop is for the final dictionary to contain 30 items corresponding to the 30 temporary dictionaries that were generated every iteration in the loop.

However, every time I run the program I obtain a final dictionary that contains only 9 items, corresponding to some, but not all, temporary dictionaries that were generated in the loop.
Does anyone have any idea as to why this happens?
(I’m working on Python 3.7.9)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Dictionary keys are unique. rd_key = random.randint(1, 10) can produce 9 unique keys: [1,2,3,4,5,6,7,8,9]. Thus, the maximum size of final_dictionary is 9 elements.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading