Home > Blockchain >  Identify changed values between two list of dictionaries
Identify changed values between two list of dictionaries

Time:06-13

I have two lists of dictionaries as below:

old = [{'a': 'aa', 'b': 'bb', 'c': 'cc'}, {'a': 'aaa', 'b': 'bbb', 'c': 'ccc'}]

new = [{'a': 'aa', 'b': 'boy', 'c': 'cc'}, {'a': 'aaa', 'b': 'bbb', 'c': 'cat'}]

In every dictionary in new and old list, the keys are 'a', 'b', 'c'. I need to identify the difference if any in the values. In the example above ideally I want the output to be 'b' and 'c' as the values for those keys have changed. Just identify keys whose values have been modified.

How should I implement this? Thanks!

CodePudding user response:

To compare two dictionaries, use something like this:

having dictionaries d1 and d2

differences={key: ( d1[key], d2[key]) for key in d1 if key not in d2 or d1[key]!=d2[key]}

CodePudding user response:

This will compare values from the first dictionary and check if its value is different from the second dictionary. If so, it will yield it.

However, this function will NOT yield keys that exist in one dictionary but not the other.

This is a generator function, so remember to iterate along it or evaluate it with list(...).

old = [{'a': 'aa', 'b': 'bb', 'c': 'cc'}, {'a': 'aaa', 'b': 'bbb', 'c': 'ccc'}]
new = [{'a': 'aa', 'b': 'boy', 'c': 'cc'}, {'a': 'aaa', 'b': 'bbb', 'c': 'cat'}]

def difference(a, b):
    for first, second in zip(a, b):
        for key, value in first.items():
            if key in second:
                if value != second[key]:
                    yield key

print(list(difference(old, new)))
> python .\diff.py
['b', 'c']

CodePudding user response:

Try this snippet to see it helps you:

d1 = [{'a': 'aa', 'b': 'bb', 'c': 'cc'}, 
       {'a': 'aaa', 'b': 'bbb', 'c': 'ccc'}]

d2 = [{'a': 'aa', 'b': 'boy', 'c': 'cc'},
       {'a': 'aaa', 'b': 'bbb', 'c': 'cat'}]
   
for d1, d2 in zip(d1, d2):
    #print(d1, d2)         # get each dict from d1 and d2
    for k in d1:           # start to check the key from old (d1)
        if k in d2 and d1[k] != d2[k]:
            print(k)       # b  then c
  • Related