简体   繁体   English

如何在字典中按值访问键?

[英]How to access key by value in a dictionary?

I have a dict that looks like the following: 我有一个看起来如下的字典:

d = {"employee": ['PER', 'ORG']}

I have a list of tags ('PER', 'ORG',....) that is extracted from the specific entity list . 我有一个从特定entity list提取的tags ('PER', 'ORG',....)列表tags ('PER', 'ORG',....)

for t in entities_with_tag: # it includes words with a tag such as: [PER(['Bill']), ORG(['Microsoft']), 
    f = t.tag # this extract only tag like: {'PER, ORG'}
    s =str(f)
    q.add(s)

Now I want if {'PER, ORG'} in q , and it matched with d.values() , it should give me the keys of {'PER, ORG'} which is 'employee' . 现在我想要q {'PER, ORG'} ,并且它与d.values()相匹配,它应该给我{'PER, ORG'}keys ,即'employee' I try it this but does not work. 我试试这个,但不起作用。

for x in q:
   if str(x) in str(d.values()):
       print(d.keys()) # this print all the keys of dict.

If I understand correctly you should loop he dictionary instead of the tag list. 如果我理解正确,你应该循环他的字典而不是标签列表。 You can check if the dictionary tags are in the list using sets. 您可以使用集合检查字典标记是否在列表中。

d = {"employee": ['PER', 'ORG'],
    "located": ["ORG", "LOC"]}
q = ["PER", "ORG", "DOG", "CAT"]
qset = set(q)
for key, value in d.items():
    if set(value).issubset(qset):
        print (key)

Output: 输出:

employee

You mean with... nothing? 你的意思是......什么都没有?

for x in q:
   if str(x) in d.values():
       print(d.keys())

What you can do is to switch keys and values in the dict and then access by key. 你可以做的是切换字典中的键和值,然后通过键访问。

tags = ('PER', 'ORG')
data = dict((val, key) for key, val in d.items())
print(data[tags])

Just be careful to convert the lists in tuples, since lists are not hashable. 请小心转换元组中的列表,因为列表不可清除。

Another solution would be to extract both key and value in a loop. 另一种解决方案是在循环中提取键和值。 But that's absolutely NOT efficient at all. 但这绝对没有效率。

for x in q:
    if str(x) in str(d.values()):
        for key, val in d.items():
            if val == x:
                print(key) # this print all the keys of dict.

What you can do is make two lists. 你可以做的是制作两个清单。 One which contains the keys and one which contains the values. 一个包含键,另一个包含值。 Then for the index of the required value in the list with values you can call the key from the list of keys. 然后,对于具有值的列表中所需值的索引,您可以从键列表中调用键。

    d = {"employee": ['PER', 'ORG']}

    key_list = list(d.keys()) 
    val_list = list(d.values()) 

    print(key_list[val_list.index(['PER','ORG'])

Refer: https://www.geeksforgeeks.org/python-get-key-from-value-in-dictionary/ 参考: https//www.geeksforgeeks.org/python-get-key-from-value-in-dictionary/

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

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