【问题标题】:Compare 2 nested dicts and show differences比较 2 个嵌套字典并显示差异
【发布时间】:2017-10-30 20:01:09
【问题描述】:

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

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'}}

我需要比较 slownikAG 中的密钥是否为“3”,例如:
检查slownikAE 中是否为“1614519” -
检查slownikAE 中是否为“45771661” - 是 - 将其放入新字典
检查slownikAE 中是否为“45771789” - 是 - 将其放入新字典

输出:

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

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

for male in slownikAG:
    dane = slownikAG[male]
    i = 1
    while i < zakladka2.max_row-1:
        if str(dane[3]) in slownikAE[i][1]:
            print("Exists")
            print(str(dane[3])+" : "+str(slownikAE[i]))
        else:
            print("Missing "+str(dane[3]))
        i += 1

【问题讨论】:

  • 什么是zakladka2.max_row?在一个地方,您谈到创建一个新字典,但您的比较代码只是打印一些东西——那么您到底想要做什么?

标签: python dictionary nested compare


【解决方案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'}}

【讨论】:

  • 谢谢,但它不起作用 - 它返回空的“final_dict”字典。而且我无法更改“slownikAG”和“slownikAE”的布局 - 因为它与 Excel 文件相连 - 我已将 Excel 中的数据放入字典,我想避免更改字典的结构。
  • @Kris 你是什么意思?有什么错误或问题?
猜你喜欢
  • 2020-10-19
  • 1970-01-01
  • 2019-08-03
  • 1970-01-01
  • 1970-01-01
  • 2023-03-26
  • 1970-01-01
  • 1970-01-01
  • 2014-07-15
相关资源
最近更新 更多