This question already has answers here:
Comparing Python dictionaries and nested dictionaries
                                
                                    (4个答案)
                                
                        
                                上个月关闭。
            
                    
我在与列表中的嵌套字典进行比较时遇到了麻烦,我试图仅显示键值发生变化的数据以及它们之间的差异。我已经尝试过了(示例已简化,比较数据中可以有不同级别的嵌套):

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


但是,当我运行此命令时,仍然看到相同的键:


  [{'poker':{'John':{'Wins':6,6,'Losses':1},'Jack':{'Wins':6,
  'Losses':5},'Bill':{'Wins':3,'Losses':0}}},{'Blackjack':
  {'Bill':{'Wins':4,4,'Losses':3},'John':{'Wins':7,'Losses':0},
  '杰克':{'胜利':1,'亏损':3}}}}]


我希望看到的是:


  [{“ poker”:{“ John”:{“ Wins”:6},“ Jack”:{“ Loss”:5},“ Bill”:{“ Wins”:
  3,“亏损”:0}}},{“二十一点”:{“杰克”:{“胜利”:1,“亏损”:3}}}}]


如果我能看到新旧之间的数字差异,那将是很好的,但是我只想显示变化了。

最佳答案

我认为您的代码中只有一个小错误,如果您对其进行修复,一切将按预期进行

线

type(new(key)) == dict


总是失败,因为您应该使用new [key]访问字典的元素。如果在内部尝试,您可以替换该行

if isinstance(new[key], dict)


顺便说一句,制作这种无声的try except绝不是一个好主意。

关于python - python嵌套字典比较,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49739102/

10-11 17:23