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)
CodePudding user response:
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.