大家晚上好,
希望你们一切都好。
我的目标 我正在尝试将一个字典的值匹配到另一个字典的键。
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
dict2
的完整示例会更有帮助。 - Mark