使用“If key in dict:”在python字典中搜索键似乎不起作用

2024-04-18 14:50:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我遍历一个csv文件并检查一个列是否作为关键字出现在字典中。你知道吗

这是CSV文件中的一个示例行

833050,1,109,B147599,162560,0

我在查第五栏是否是这本词典的关键字

{162560: True, 165121: True, 162562: True, 153098: True, 168336: True}

我在下面的代码中传递这个dict作为变量mt\u预算

def check(self, mt_budgets):
    present = {}
    cwd = os.getcwd()
    path = cwd 
    with open(path + 'file.csv.part') as f:
        csv_f = csv.reader(f)
        for row in csv_f:
            if row[4] == '162560':
                print 'Yes STRING'
                if str(row[4]) in mt_budgets:
                    print 'Yes it\'s here'
                    present[row[4]] = True
                else:
                    print 'No it\'s not'
                    print row[4]
                    print mt_budgets

这是我得到的结果

Yes STRING
No it's not
162560
{162560: True, 165121: True, 162562: True, 153098: True, 168336: True}

我不知道它为什么不把它当成钥匙,这是怎么回事?你知道吗

谢谢!你知道吗


Tags: 文件csvpathintrueifit关键字
1条回答
网友
1楼 · 发布于 2024-04-18 14:50:58
{162560: True} # {int:bool}
{'162560': True} # {str:bool}

所以,mt_budgets不包含'162560'(str),它包含162560(int)

您的代码应该是:

def check(self, mt_budgets):
    present = {}
    cwd = os.getcwd()
    path = cwd 
    with open(path + 'file.csv.part') as f:
        csv_f = csv.reader(f)
        for row in csv_f:
            if int(row[4]) == 162560:  # csv data is possibly str format. convert it to int and compare.
                print 'Yes STRING'
                if int(row[4]) in mt_budgets:
                    print 'Yes it\'s here'
                    present[row[4]] = True
                else:
                    print 'No it\'s not'
                    print row[4]
                    print mt_budgets

相关问题 更多 >