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

3

大家晚上好,

希望你们一切都好。

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

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循环编写为以下形式,那么代码就可以运行:


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


2
如果您提供一个包括 dict2 的完整示例会更有帮助。 - Mark
@MarkMeyer。谢谢,示例已提供。 - IniMzungu
1个回答

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

感谢@MarkMeyer和pavel的反馈和耐心。我是编程新手,Stackoverflow是我唯一能谈论编程的地方,所以对于缺乏澄清表示歉意。看起来我需要阅读有关集合的资料。 - IniMzungu
谢谢提到Python之禅@pavel(您的评论已经消失了),我会去阅读一下。我正在忙于阅读《程序员修炼之道》。 - IniMzungu
1
@XpLoDe-NeF的集合非常棒。对于这种情况,它们比嵌套循环快得多。 - Mark

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接