Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access key by value in a dictionary?

Tags:

python

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.

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'. 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.
like image 980
Zia Avatar asked Dec 05 '25 16:12

Zia


2 Answers

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
like image 162
Hirabayashi Taro Avatar answered Dec 08 '25 04:12

Hirabayashi Taro


You mean with... nothing?

for x in q:
   if str(x) in d.values():
       print(d.keys())
like image 29
U12-Forward Avatar answered Dec 08 '25 06:12

U12-Forward



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!