gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 05:00:33 28 4
gpt4 key购买 nike

晚安

希望你一切都好。

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

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():会工作。

如有任何反馈,我们将不胜感激。

@马克迈耶

请求的示例值:

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

关于python - 将一个字典的值与另一个字典的键匹配 (Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63083132/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com