我使用的是 Python 3。我有 3 个组,在这些组中我有多个值。
我有我搜索的值(value),我想得到他的组。例如,如果我有 CCC
,我需要得到 GROUP 1
,如果我有 HHH
,我想要 GROUP 3
然后根据小组做一些事情。
所以我想我会像这样创建一个字典(如果我错了请告诉我):
{
'group1': {'AAA','BBB','CCC','DDD'},
'group2': {'EEE','FFF','GGG'},
'group3': {'HHH','JJJ'}
}
所以我看到我们可以恢复字典以从值中获取键,所以我想这样做:
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
但我认为这不是做我想做的事情的好方法。有一种方法可以做这样的事情:
if 'CCC' in dict :
# Then get the current key. How ?
或者也许我不需要创建 dict 而是其他东西?我愿意接受你所有的建议。
最佳答案
您的反向 dict
(通常称为倒排索引)将失败,因为您使用集合作为键。集合是可变的,它们不能被散列以形成 dict
键。相反,您可能希望组中的每个元素 形成一个键。
您可以使用 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
在倒排索引中,一个元素可能有多个键指向它(即使在您的数据中并非如此),这就是为什么每个值都必须是键的集合
。
如果正如您在评论中所说的那样,您的数据肯定只有一对一的对应关系,那么您可以简单地创建一个dict
。
inverted_index = {element: name for name, group in groups.items() for element in group}
print(inverted_index)
输出
{'AAA': 'group1',
'BBB': 'group1',
'CCC': 'group1',
'DDD': 'group1',
'EEE': 'group2',
'FFF': 'group2',
'GGG': 'group2',
'HHH': 'group3',
'JJJ': 'group3'}
关于python - 在字典中找到一个值然后得到键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52647395/