简体   繁体   English

即使密钥存在,也检查 dict 中的密钥是否返回 false

[英]Check for key in dict returning false even though the key exists

I've this function:我有这个 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.我还尝试if 'my-topic-1' in topics.keys()但得到了相同的结果。

What am I doing wrong?我究竟做错了什么?

As said in the comments, this happens because your keys are bytes not str .正如评论中所说,发生这种情况是因为您的键是bytes而不是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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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