How to subtract dictionaries from a list

107
November 30, 2019, at 7:40 PM

I have a list of dictionaries (not all in the same length) like -

[{x:3, y:5}, {x:2, z:1}, {y:2}]

And would like to get a new dictionary that subtract the values of the same key -

{x:1, y:3, z:1}

I tried to run on each dictionary but couldnt understand how to make the subtraction

Answer 1

You can use something thing like the following.

new_dict = {}
for dict in list:
    for k,v in dict.items():
        new_dict[k] = (new_dict[k] - v) if k in new_dict else v
Answer 2

Create a new dictionary. In a loop over the source sequence, modify the original dictionary - this also involves a loop over the keys therein. The end dictionary will be the desired result.

It is potentially unclear why z should be 1 and not -1; in any case, with a loop this logic can be clearly teased out; ie. add key on first-seen, subtract from the existing value otherwise.

The pseudo code might then look something like the following, which has a near 1-1 translation to Python:

let result be an empty dictionary
for every group in groups
     for each pair of k,v in group
         if result contains k then
             subtract v from result[k] and store in result[k]
         otherwise (if it does not exist yet)
             store the value of v in result[k]

Make sure to follow only with the Python constructs at each step of the transliteration to understand the process.

READ ALSO
How can I store these values?

How can I store these values?

I'm learning how to code in Python and I have this problem: I want to store the output values of a function (function2) that depends on another function (Function1)I want to store them in order to compute its mean, variance, etc

90
How to count how often a Function was accessed?

How to count how often a Function was accessed?

So i have the Function Ball() for exampleand in that Function i have imported a list with Ball names where i randomly choose one and return that name

68
Progress bar keeps on freezing the whole app

Progress bar keeps on freezing the whole app

I am trying to create an app using aioavast and pyqt5 (basically, I'm making an antivirus) however when I try to implement the scanning process and connect the command together, The whole app freezes

88
Can type given word with a [N]x[M] keyboard? [closed]

Can type given word with a [N]x[M] keyboard? [closed]

Want to improve this question? Add details and clarify the problem by editing this post

81