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

Viewed 365

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?

1 Answers

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()
Related