Python 比较两个嵌套的dict并显示差异
我有一个简单的问题,但我无法解决。 我有两个嵌套字典:Python 比较两个嵌套的dict并显示差异,python,dictionary,nested,compare,Python,Dictionary,Nested,Compare,我有一个简单的问题,但我无法解决。 我有两个嵌套字典: 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: '55
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'}}
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
如果在slownikAG
中有键“3”,我需要进行比较,例如:检查
slownikAE
中是否为“1614519”-否检查
slownikAE
中是否为“45771661”-是-将其放入新词典中检查
slownikAE
中是否为“45771789”-是-将其放入新词典中输出:
newwdictionary = {1: {1: '45771661', 2: '5500007672', 3: 'RM'},
2: {1: '45771789', 2: '5500007673', 3: 'RM'}}
{1: {1: '45771661', 2: '5500007672', 3: 'RM'}, 2: {1: '45771789', 2: '5500007673', 3: 'RM'}}
我已经用我的代码尝试了很多次,但是我在比较这两个字典时遇到了很大的困难:
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'}}
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
对于斯洛尼卡男性:
丹麦=斯洛尼卡[男性]
i=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)}
输出:
newwdictionary = {1: {1: '45771661', 2: '5500007672', 3: 'RM'},
2: {1: '45771789', 2: '5500007673', 3: 'RM'}}
{1: {1: '45771661', 2: '5500007672', 3: 'RM'}, 2: {1: '45771789', 2: '5500007673', 3: 'RM'}}
谢谢,但它不起作用-它返回空的“最终dict”字典。我不能更改“slownikAG”和“slownikAE”的布局-因为它与Excel文件连接-我已将Excel中的数据放入字典,我希望避免更改字典的结构。@Kris你是什么意思?错误或问题是什么?zakladka2.max_行是什么?在一个地方,您谈到创建一个新的字典,但是您的比较代码只是打印一些东西,那么您到底想做什么呢?