I'm having trouble doing a comparison against nested dictionaries in a list, I'm trying to only show the data for keys where the values changed, and the difference between them. I've tried this (example is simplified, there can be different levels of nesting in my comparison data):
old = [{"poker":{"John":{"Wins": 4, "Losses": 3}, "Jack": {"Wins": 6, "Losses": 1}}},
{"Blackjack":{"Bill": {"Wins": 4, "Losses": 3}, "John": {"Wins": 7, "Losses": 0}}}]
new = [{"poker":{"John":{"Wins": 6, "Losses": 3}, "Jack": {"Wins": 6, "Losses": 5}, "Bill": {"Wins": 3, "Losses": 0}}},
{"Blackjack":{"Bill": {"Wins": 4, "Losses": 3}, "John": {"Wins": 7, "Losses": 0}, "Jack":
{"Wins": 1, "Losses": 3}}}]
def nested_compare(new, old):
for key in new:
try:
if type(new(key)) == dict:
nested_compare(old[key], new[key])
except:
pass
oldkeys = set(old.keys())
newkeys = set(new.keys())
samekeys = newkeys.intersection(oldkeys)
unchanged = set(k for k in samekeys if old[k] == new[k])
for key in list(unchanged):
try:
del new[key]
del old[key]
except KeyError:
pass
return new, old
final = []
x = 0
for entry in new:
new_data, old_data = nested_compare(entry, old[x])
x += 1
final.append(new_data)
print final
However, when I run this, I still see the keys that are the same:
[{'poker': {'John': {'Wins': 6, 'Losses': 1}, 'Jack': {'Wins': 6, 'Losses': 5}, 'Bill': {'Wins': 3, 'Losses': 0}}}, {'Blackjack': {'Bill': {'Wins': 4, 'Losses': 3}, 'John': {'Wins': 7, 'Losses': 0}, 'Jack': {'Wins': 1, 'Losses': 3}}}]
And what I expect to see:
[{"poker":{"John":{"Wins": 6}, "Jack": {"Losses": 5}, "Bill": {"Wins": 3, "Losses": 0}}}, {"Blackjack": {"Jack":{"Wins": 1, "Losses": 3}}}]
It would be nice if I could see the number differences between the old and new, but I'll just settle to only show what changed.