简体   繁体   中英

Check for key in dict returning false even though the key exists

I've this function:

def step_list_kafka_topics(context):
    topics = context.kafka.list_kafka_topics()
    if 'my-topic-1' in topics:
        print('TRUE: {}'.format(topics))
    else:
        print('FALSE {}'.format(topics))

This is the response I get:

FALSE {b'my-topic-1': None, b'my-topic-2': None, b'my-topic-3': None}

I also tried if 'my-topic-1' in topics.keys() but got the same result.

What am I doing wrong?

As said in the comments, this happens because your keys are bytes not str . So, one way to fix that is to decode them back to string like the following:

def step_list_kafka_topics(context):
    topics = context.kafka.list_kafka_topics()
    topics = {key.decode("utf-8") for key in topics}  #<-- just add this
    if 'my-topic-1' in topics:
        print('TRUE: {}'.format(topics))
    else:
        print('FALSE {}'.format(topics))
print()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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