嗨,我正在尝试编写一些代码,该代码比较多个嵌套词典与特定项目的匹配情况,如果为true,则返回外键。
我尝试使用嵌套的for循环和字典名称列表来排序和查找匹配项,代码首先获取单个字典dict1和dict2,然后比较每个字典中的['ID']键进行匹配,请参见下文:
Dictionary1 = {'key1':{'ID':'ID1'}, 'key2':{'ID':'ID2'}, 'key3':{'ID':'ID3'}}
Dictionary2 = {'key4':{'ID':'ID1'}, 'key5':{'ID':'ID2'}, 'key6':{'ID':'ID3'}}
DictionaryList = [Dictionary1, Dictionary2]
for Dict1 in DictionaryList:
for Dict2 in DictionaryList:
for Key1 in Dict1:
for Key2 in Dict2:
if Dict1[Key1]['ID'] == Dict2[Key2]['ID']:
print('Dictionary1' + ': ' + Key1 + ' // ' 'Dictionary2' + ': ' + Key2)
此代码返回12个匹配项及其外键,其中大多数是错误的,请参见下文:
Dictionary1: key1 // Dictionary2: key1
Dictionary1: key2 // Dictionary2: key2
Dictionary1: key3 // Dictionary2: key3
Dictionary1: key1 // Dictionary2: key4
Dictionary1: key2 // Dictionary2: key5
Dictionary1: key3 // Dictionary2: key6
Dictionary1: key4 // Dictionary2: key1
Dictionary1: key5 // Dictionary2: key2
Dictionary1: key6 // Dictionary2: key3
Dictionary1: key4 // Dictionary2: key4
Dictionary1: key5 // Dictionary2: key5
Dictionary1: key6 // Dictionary2: key6
我怀疑这是因为字典彼此匹配数次,即代码将Dictionary1与Dictionary1比较,然后将Dictionary2与Dictionary2比较,依此类推。
预期结果将是打印3个匹配项的代码:
Dictionary1: key1 // Dictionary2: key4
Dictionary1: key2 // Dictionary2: key5
Dictionary1: key3 // Dictionary2: key6
我是python / programming的新手,所以将不胜感激。
答案 0 :(得分:0)
我不确定您为什么将字典合并到一个列表中,然后尝试对其进行迭代。您本可以简单地使用字典本身:
for Key1 in Dictionary1:
for Key2 in Dictionary2:
if Dictionary1[Key1]['ID'] == Dictionary2[Key2]['ID']:
print('Dictionary1' + ': ' + Key1 + ' // ' 'Dictionary2' + ': ' + Key2)
这将打印
Dictionary1: key1 // Dictionary2: key4
Dictionary1: key2 // Dictionary2: key5
Dictionary1: key3 // Dictionary2: key6
答案 1 :(得分:0)
您可以创建一个反向映射字典,将Dictionary2
中的ID映射到其键,以便通过迭代Dictionary1
并将每个ID映射到对应的ID,从而在线性时间内获得所需的输出。通过反向映射字典键入Dictionary2
:
mapping = {d['ID']: k for k, d in Dictionary2.items()}
for k, d in Dictionary1.items():
print('Dictionary1' + ': ' + k + ' // ' 'Dictionary2' + ': ' + mapping[d['ID']])
这将输出:
Dictionary1: key1 // Dictionary2: key4
Dictionary1: key2 // Dictionary2: key5
Dictionary1: key3 // Dictionary2: key6