在Python中比较两个字典中的值

2024-05-16 13:44:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我被困在我的编码中间,因为: 我有两本字典如下:

a = {0:['1'],1:['0','-3']}
b = {'box 4': ['0 and 2', '0 and -3', ' 0 and -1', ' 2 and 3'], 'box 0': [' 1 ', ' 1 and 4 ', ' 3 and 4']

我想找出第一个字典中的值是否与第二个字典中的值匹配,如果匹配,我想返回字典b中匹配的键和值

例如:比较的结果将返回box4,['0','-3'],因为['0','-3']a中的一个项目,它也在b['0 and -3']中找到,但是如果只找到了'3',我不希望它返回任何东西,因为没有与它匹配的值。结果还将返回box0['1'],因为它是a中的一个项,并且在b中也找到了它。你知道吗

有什么想法吗?我很感激你的帮助。你知道吗


Tags: and项目box编码字典box4box0
2条回答

你说,“比较的结果将返回方框4,因为['0','-3']是a中的一个项目,它也在b['0和-3']中找到。”。我在b中没有看到'0 and -3'

而且,你的问题还不够清楚。您的代码片段不完整,这里只介绍了一个案例。你知道吗

尽管如此,我还是会错误地认为你想要这样的东西

normalized_values = set([" and ".join(tokens) for tokens in a.values()])
for k in b:
    if normalized_values.intersection(set(b[k])):
        print k

给你:简单编码

>>> a_values = a.values()
>>> for x,y in b.items():
...     for i in y:
...         i = i.strip()
...         if len(i)>1:
...             i = i.split()[::2]
...             if i in a_values:
...                 print x,i
...         else:
...             if list(i) in a_values:
...                 print x,list(i)
box 4 ['0', '-3']
box 0 ['1']

脓道:

>>> [ [x,i] for x,y in b.items() for i in y if re.findall('-?\d',i) in a_values ]
[['box 4', ' 0 and -3'], ['box 0', ' 1 ']]

相关问题 更多 >