Home > database >  I am getting different value when printing and appending same variable to a list, Why is that?
I am getting different value when printing and appending same variable to a list, Why is that?

Time:11-09

The first code gives me the output I want but I want the dct to append to a list so I can use the values later. When I try to do that it gives me a different output. Why?

lst = [{'a' : 1, 'b' : 2, 'c': 3 },{'e' : 1, 'f' : 2, 'g': 3}]
e = 0
while e < len(lst):
    for k in lst[e]:
        dct = {}
        x = lst[e][k]
        for key, value in lst[e].items():
            lst[e][key] = (value - x)
            dct[k] = (lst[e])
        print(dct)
    e  = 1

output(lst) = {'a': {'a': 0, 'b': 1, 'c': 2}}
              {'b': {'a': -1, 'b': 0, 'c': 1}}
              {'c': {'a': -2, 'b': -1, 'c': 0}}
              {'e': {'e': 0, 'f': 1, 'g': 2}}
              {'f': {'e': -1, 'f': 0, 'g': 1}}
              {'g': {'e': -2, 'f': -1, 'g': 0}}

So the following is what I tried to do to save it in a list

e = 0
lst2 = []
while e < len(lst):
    for k in lst[e]:
        dct = {}
        x = lst[e][k]
        for key, value in lst[e].items():
            lst[e][key] = (value - x)
            dct[k] = (lst[e])
        lst2.append(dct)        
    e  = 1
print(lst2)

But the output when I print that list gives me the same value for every key in the different dictionaries.

Output(lst2)= [{'a': {'a': -2, 'b': -1, 'c': 0}}, 
               {'b': {'a': -2, 'b': -1, 'c': 0}}, 
               {'c': {'a': -2, 'b': -1, 'c': 0}}, 
               {'e': {'e': -2, 'f': -1, 'g': 0}}, 
               {'f': {'e': -2, 'f': -1, 'g': 0}}, 
               {'g': {'e': -2, 'f': -1, 'g': 0}}]

CodePudding user response:

If you want to use your existing code, change

lst2.append(dct)

to

lst2.append(dct.copy())

(and to understand why, read up on lists, references, and mutability.)

Or, if you want to rewrite your code, you might use

list_ = [{'a' : 1, 'b' : 2, 'c': 3 },{'e' : 1, 'f' : 2, 'g': 3}]

result = {}
for d in list_:
    for key, value in d.items():
        result[key] = {k:d[k]-value for k in d}

which gives

>>> print(result)
{'a': {'a':  0, 'b':  1, 'c': 2},
 'b': {'a': -1, 'b':  0, 'c': 1},
 'c': {'a': -2, 'b': -1, 'c': 0},
 'e': {'e':  0, 'f':  1, 'g': 2},
 'f': {'e': -1, 'f':  0, 'g': 1},
 'g': {'e': -2, 'f': -1, 'g': 0},
}

(and if you're a fan of code-golf, here's a one-liner:)

result = {key: {k:d[k]-value for k in d} for d in list_ for key,value in d.items()}
  • Related