0

I have a Queue (size 30) with lines (got from requests r). Those lines are each dictionaries, how can I look if a dict contains a key 'example'?

def process_queue(queue):
    count = 0
    for line in queue.get():
        count = count + 1
        if 'venue' in dict():
            print ('Yes')
        else:
            print ('No')
        if count == 30:
            break

1 Answers1

-1

If you want to check if a dictionary contains a certain key, you can use

if example in list(yourDict.keys()):
    # do what you want here

list(yourDict.keys()) will be a list of all the keys in yourDict, in no particular order (where yourDict is a dictionary. This basically reads like an English sentence: "If example is an item in the list, then do something."

pianoman24
  • 43
  • 1
  • 7
  • Could you explain a little bit more? @user6003925 – Christian Van de Koppel Jun 26 '17 at 17:18
  • 1
    `if example in list(yourDict.keys())` - oh hell no. This is doubly terrible, first because you're calling `keys` (unnecessary, and on Python 2, it's slow and prevents a quick hash table lookup), and second because you're calling `list` (slow, unnecessary, and prevents a hash table lookup on any version of Python). The right way to check whether a dict has a particular key is `example in yourDict`. – user2357112 Jun 26 '17 at 18:46