Reputation: 11
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?
Upvotes: 0
Views: 73
Reputation: 4653
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
Upvotes: 0
Reputation: 1229
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.
Upvotes: 1