0

I want to check whether my key is equal to the input:

topics = c.classify("what about ")
a = topics.keys() 
if a == "resources": 
    print("yes")

But a is stored as dict_keys(['resource"]) I want a to be just "resources". can anyone help me on this,please?

Pika Supports Ukraine
  • 3,612
  • 10
  • 26
  • 42

2 Answers2

1

You should first convert the keys into regular python list and then iterate in it (You probably can do it without converting, but I think it is more simple to find).

topics = c.classify("what about ")
a = list(topics.keys())
for key in a:
    if key == "resources": 
        print("yes")

Don't forget a dict can have multiple values. As @rob-bricheno said, you can do it simpler with in operator. This operator will loop through the list and if the element you've specified is in it, return True, otherwise it will return False value. So you can do it with this simplified code:

topics = c.classify("what about ")
a = list(topics.keys())
if "resources" in a:
    print("yes")

When resources is in the a list, if condition is True, so the print will call. When it is not in the a, print will skip.

Mr Alihoseiny
  • 1,202
  • 14
  • 24
  • Your welcome. If it was helpful, you can flag it as correct answer. so other people those have same problem as you, can find it is their solution when reviewing this question on stackoverflow. It will be good if you do it in all your questions in stackoverflow. – Mr Alihoseiny Nov 16 '18 at 18:08
  • Yes. But I think it is complicated for a person who is new in python. – Mr Alihoseiny Nov 16 '18 at 18:19
0

You can use in. When you use this with a dictionary, it checks if the value you've specified is a key in the dictionary.

topics = c.classify("what about ")
if "resources" in topics:
    print("yes")

This is the fastest and most standard way to do this. Read here for more Python dictionary keys. "In" complexity

Rob Bricheno
  • 4,467
  • 15
  • 29