简体   繁体   English

在字典中找到一个值,然后获取密钥

[英]Find a value in dict then get the key

I'm using Python 3. I have 3 groups and in these groups I have multiple values. 我正在使用Python3。我有3个组,在这些组中,我有多个值。 在此处输入图片说明

I have the value that I search and I want to get his group. 我具有所寻找的价值,并且希望得到他的支持。 For example if I have CCC I need to get GROUP 1 and if I have HHH I want the GROUP 3 then do something according to the group. 例如,如果我有CCC ,则需要获得GROUP 1 ;如果我有HHH我需要GROUP 3然后根据组进行一些操作。

So I think I gonna create a dict like this (tell me if I'm wrong) : 所以我想我要创建一个这样的字典(如果我写错了,请告诉我):

{
  'group1': {'AAA','BBB','CCC','DDD'}, 
  'group2': {'EEE','FFF','GGG'},
  'group3': {'HHH','JJJ'}
}

So I see that we can revert the dict to get the key from a value so I thought to do this : 所以我看到我们可以还原dict以从一个值获取密钥,所以我想这样做:

dict = {
  'group1': {'AAA','BBB','CCC','DDD'},
  'group2': {'EEE','FFF','GGG'},
  'group3': {'HHH','JJJ'}
}

revdict = dict([(dict[key],key) for key in dict])

group = revdict['CCC']
if group == 'group1':
    # Do something
elif group == 'group2':
    # Do something
elif group == 'group3':
    # Do something

But I don't think it's the good way to do what I want. 但是我认为这不是做我想要的事情的好方法。 There is a way to do something like this : 有一种方法可以执行以下操作:

if 'CCC' in dict :
    # Then get the current key. How ?

Or maybe I don't need to create dict but another things ? 或者,也许我不需要创建dict而是其他东西? I open for all your suggestions. 我接受您的所有建议。

Your reversed dict , commonly called an inverted index, will fail because you are using sets as keys. 您的反向dict (通常称为反向索引)将失败,因为您将集合用作键。 Sets being mutable, they cannot be hashed to form a dict key. 集合是可变的,它们不能被散列以形成dict键。 Instead, you probably wanted each element of a group to form a key. 相反,您可能希望组中的每个元素形成一个键。

You can rewrite the correct inverted index with a defaultdict . 您可以使用defaultdict重写正确的反向索引。

from collections import defaultdict

groups = {
    'group1': {'AAA', 'BBB', 'CCC', 'DDD'},
    'group2': {'EEE', 'FFF', 'GGG'},
    'group3': {'HHH', 'JJJ'}
}

inverted_index = defaultdict(set)

for name, group in groups.items():
    for element in group:
        inverted_index[element].add(name)

print('group1' in inverted_index['AAA']) # True
print('group1' in inverted_index['EEE']) # False

In an inverted index, an element may have multiple keys pointing to it (even though it is not the case in you data), this is why each value must be a set of keys. 在倒排索引中,一个元素可能有多个指向它的键(即使您的数据中不是这种情况),这就是为什么每个值都必须是一set键的原因。

If, as you seem to state it in the comments, your data is assured to only have one-to-one correspondences, then you can simply create a dict . 如您似乎在评论中指出的那样,如果确保您的数据仅具有一对一的对应关系,那么您可以简单地创建一个dict

inverted_index = {element: name for name, group in groups.items() for element in group}
print(inverted_index)

Output 产量

{'AAA': 'group1',
 'BBB': 'group1',
 'CCC': 'group1',
 'DDD': 'group1',
 'EEE': 'group2',
 'FFF': 'group2',
 'GGG': 'group2',
 'HHH': 'group3',
 'JJJ': 'group3'}

You can retrieve the key using list comprehension and only returning the key if the str you are looking for is in its values 您可以使用列表推导来检索key并且仅在要查找的str包含其values时才返回key

d = {
  'group1': {'AAA','BBB','CCC','DDD'},
  'group2': {'EEE','FFF','GGG'},
  'group3': {'HHH','JJJ'}
}

a = [i for i in d if 'CCC' in d[i]]
# ['group1']

I you insist on not using index for the key, 我坚持不使用索引作为密钥,

answer = None
for key in d.keys():
   if "CCC" in d[key]:
      answer = key
      break

*edit suggested by @Olivier * @ Olivier建议的编辑

for k,v in dict.items():
   if 'CCC' in v:
      print(k)

you can't escape loops or reverse dicts. 您无法逃避循环或反向指令。 if you don't have memory constraints use your reverse dict. 如果您没有内存限制,请使用逆向字典。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM