Home > Software design >  Multiple same name dictionaries in a list with each instance in the list having different dictionary
Multiple same name dictionaries in a list with each instance in the list having different dictionary

Time:10-21

First off: I don't really know how to correctly phrase this question, the idea is as follows:

I have a standard dictionary that I want to check values in, with different objects using that dictionary to check items to. Now if I'm working in a specific object and append data to the dictionary of that object, the data gets appended to all dictionaries within all objects... How do I change this so that working in one object does not alter the dictionaries in another object? Below you can find the general gist of what I would like to do:

def main():
    class Header:
        dict = {1: [], 2: []}

    l = [1, 1, 1]
    headerDicts = []

    for item in l:
        if item in Header.dict:
            headerDicts.append(Header.dict)
            headerDicts[len(headerDicts)-1][item].append(5)

    print(headerDicts)

if __name__ == '__main__':
    main()

Running this produces the following:

[{1: [5, 5, 5], 2: []}, 
 {1: [5, 5, 5], 2: []}, 
 {1: [5, 5, 5], 2: []}]

What I would like is the following:

[{1: [5], 2: []}, 
 {1: [5], 2: []}, 
 {1: [5], 2: []}]

So that each dictionary in the list I'm creating has its own independent dictionary I can work in. So far, I've not found a solution to this problem

CodePudding user response:

The problem you faced here happens because dictionaries in Python are shared by reference but not by value. So every time you use one and the same dictionary for your operations. If you want to make sure that every time you get separate dictionary use copy() function. It will create a separate copy of the dictionary that you want and changing of which won't lead to changing everywhere. :

headerDicts.append(Header.dict.copy())

CodePudding user response:

I have done some changes in Your Code, in your code every time value append in same dictionary, by using this copy.deepcopy() will help you to make new separate dict and append value. so that it will not affect in your main dict. i think this code will help you !!

import copy
def main():
    class Header:
        dict = {1: [], 2: []}

    l = [1, 1, 1]
    headerDicts = []

    for item in l:
        if item in Header.dict:
            temp=copy.deepcopy(Header.dict)
            temp[item].append(5)
            headerDicts.append(temp)
    print(headerDicts)

if __name__ == '__main__':
    main()

Output :

[{1: [5], 2: []}, {1: [5], 2: []}, {1: [5], 2: []}]
  • Related