简体   繁体   English

Python if语句条件使用字典字符串

[英]Python if statement condition using dictionary string

I would like to use dictionary value of the key to verify if condition is true eg 我想使用密钥的字典值来验证条件是否为真,例如

dictionary = [{'Class': '>50K'},{'Class': '<=50K'}]
    for i in dictionary:

        if i['Class'] == '<=50k':
            po_list_count +=1

        else:
            rich_list_count +=1

    print(po_list_count,'---',rich_list_count)

print should be 1 --- 1 instead I get 0 --- 2 打印应该是1 --- 1而不是0 --- 2
I have tried with if i['Class'] in ['<=50k'] but same result. 我已经尝试了if i['Class'] in ['<=50k']但结果相同。
Is it something I do not understand about how if statement works or perhaps how it treats strings? 这是我不明白if语句如何工作或者它如何处理字符串的东西?

You need to check for a capital "K": 你需要检查一个大写“K”:

if i['Class'] == '<=50K':

You used one in dictionary : 你在dictionary使用了一个:

dictionary = [{'Class': '>50K'},{'Class': '<=50K'}]
#                                        here--^

在你的定义中,你使用大写<=50K并在你的if语句中使用小写k

Because k and K is not the same character. 因为kK不是同一个字符。 You'll have to match it: 你必须匹配它:

if i['class'] = '50K':

Or, a better trick: Just check both in lowercase! 或者,一个更好的技巧:只需用小写检查!

if i['class'].lower() = '50k':

Hope this helps! 希望这可以帮助!

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

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