将一个字典的值与另一个字典的键匹配(Python)

时间:2020-07-25 00:45:16

标签: python dictionary comparison

晚上全部

希望你很好。

我的目标 我正在尝试将一个字典的值与另一个字典的键匹配。

dict1有键但没有值 dict2具有键和值

dict2具有可以在dict1中作为键找到的值。我正在尝试编写代码,以识别dict2中的哪些值与dict1中的键匹配。

我的尝试 注释代码如下。

dict1 = {('dict1_key1',): [], ('dict1_key2',): []} #dictionary with keys, but no values;


for i in dict2.keys():  #iterate through the keys of dict2
    for x in dict2[i]:  #reaching every element in tuples in dict2
        if x == dict1.keys():  #if match found in the name of keys in dict1
            print(f"{i} holding {x}.") #print which key and value pair in dict 2 match the keys in dict1

如果我按如下方式编写for loop,则该代码有效:


for i in dict2.keys():  #iterate through the keys of dict2
    for x in dict2[i]:  #reaching every element in tuples in dict2
        if x == dict1_key1 or x == dict1_key2():  #if match found in the name of keys in dict1
            print(f"{i} holding {x}.") #print which key and value pair in dict 2 match the keys in dict1

但是,实际上dict1必须能够包含不同数量的键,这就是为什么我希望if x == dict1.keys():可以工作的原因。

任何反馈将不胜感激。

@Mark Meyer

根据要求提供值示例:

dict1 = {('Tower_001',): [], ('Tower_002'): []}

dict2 = {1: 'Block_A', 'Tower_001'] #first key in dict2
        #skipping keys 2 through 13
        {14: ['Block_N', 'Tower_002']#last key in dict2

1 个答案:

答案 0 :(得分:2)

您可以对dict1.keysdict2.value中的所有值进行设置。然后只需将这些集合的交集找到也是值的键即可:

dict1 = {('Tower_001',): [], ('Tower_005',): [], ('Tower_002',): []}

dict2 = {1: ['Block_A', 'Tower_001'], #first key in dict2
        14: ['Block_N', 'Tower_002']} #last key in dict2
         
         
set(k for l in dict2.values() for k in l) & set(k for l in dict1.keys() for k in l)
# {'Tower_001', 'Tower_002'}