比较2个嵌套的dicts并显示差异

时间:2017-10-30 20:01:10

标签: python dictionary nested compare

我有一个简单的问题,但我无法应对。 我有2个嵌套字典:

 def OnPaint(self, evt):
     self.DrawEntities(wx.BufferedPaintDC(self))

我需要比较,如果在slownikAG = {1: {1: 2, 2: 'DU', 3: 1614519}, 2: {1: 1, 2: 'D1', 3: 45770912}, 3: {1: 1, 2: 'D1', 3: 45771661}, 4: {1: 1, 2: 'D1', 3: 45771789}} slownikAE = {1: {1: '45771661', 2: '5500007672', 3: 'RM'}, 2: {1: '45771789', 2: '5500007673', 3: 'RM'}, 3: {1: '45771790', 2: '5500007674', 3: 'RM'}} 中我们有关键号“3”,例如: 检查slownikAG中是否为“1614519” -
检查slownikAE中是否为“45771661” - 是 - 将其放入新词典
检查slownikAE中是否为“45771789” - 是 - 将其放入新词典

输出:

slownikAE

我已经尝试了很多次使用我的代码但是我在比较这两个词典时遇到了很大的困难:

newwdictionary = {1: {1: '45771661', 2: '5500007672', 3: 'RM'},
                  2: {1: '45771789', 2: '5500007673', 3: 'RM'}}

1 个答案:

答案 0 :(得分:1)

你可以试试这个:

slownikAE = {1: {1: '45771661', 2: '5500007672', 3: 'RM'}, 2: {1: '45771789', 2: '5500007673', 3: 'RM'}, 3: {1: '45771790', 2: '5500007674', 3: 'RM'}}
vals = [1614519, 45771661, 45771789]
newdictionary = {a:b for a, b in slownikAE.items() if any(str(c) in b.values() for c in vals)}

输出:

{1: {1: '45771661', 2: '5500007672', 3: 'RM'}, 2: {1: '45771789', 2: '5500007673', 3: 'RM'}}