将一个字典的值与另一个字典的键相匹配(Python)
晚上好 希望你身体健康 我的目标 我试图将一本词典的值与另一本词典的键相匹配将一个字典的值与另一个字典的键相匹配(Python),python,dictionary,comparison,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(): #iter
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 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
实际上需要能够包含不同数量的键,这就是为什么我希望如果x==dict1.keys():可以工作的原因
如有任何反馈,将不胜感激
@马克·迈耶
所要求的数值示例:
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
您可以设置
dict1.key
和dict2.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'}
如果你能给出一个完整的例子,其中包括
dict2
@MarkMeyer,这会有所帮助。谢谢,已经提供了示例。感谢您的反馈和耐心@MarkMeyer和pavel。我是编程新手,Stackoverflow是我唯一一次谈论编程的话题,因此,对于缺乏澄清,我深表歉意。看来我需要好好阅读一下场景。谢谢你提到Python@pavel的Zen(你的评论现在不见了),我会仔细阅读的。我正忙于实用程序员的工作。@XpLoDe-NeF集很棒。对于这种情况,它们比嵌套循环快得多。