[Python] dictionary of dictionaries with same keys is changing all of the dictionaries within...

Discussão em 'Python' iniciado por Stack, Agosto 28, 2025.

  1. Stack

    Stack Membro Participativo

    I am creating a dictionary of dictionaries that all have the same keys. in my real life code the keys are "part 1":part1inventory, "part 2":part2invetory......all the way to part 17. I need to increment/decrement the partinventories by deliveries/allocations. I am also saving that entire dictionary of 17 parts and their inventories as a dictionary with the week number on it. But I am finding in my code at the end that every week dictionary is just the last week part numbers.

    Here is an example structure of the code where the part inventories are all the same for each inner dictionary at the end of the 52 weeks.

    overallpartinventories={}
    partinventories={'part a':1,'part b':2}
    overallpartinventories['Week 1']=[partinventories]

    partinventories['part a']+=1 # part a got a delivery of 1
    partinventories['part b']+=1 # part b got a delivery of 1
    overallpartinventories['Week 2']=partinventories
    overallpartinventories


    what i expected was:

    {'Week 1': [{'part a': 1, 'part b': 2}], 'Week 2': {'part a': 2, 'part b': 3}} but what I got is:

    {'Week 1': [{'part a': 2, 'part b': 3}], 'Week 2': {'part a': 2, 'part b': 3}} Why is it changing all of the inner dictionaries without me referencing the key with the associated one. I understand the variablename partinventories was linked to week 1 and week 2 but I still don't get how it's changing it when I am directly saying overallpartinventories['Week 2']=partinventories. How can overallpartinventories['Week 1'] get affected too? Is there a way to iterate over the parts list differently that will work?

    Continue reading...

Compartilhe esta Página