使用“ If key in dict:”在python词典中搜索关键字,似乎无效

时间:2018-09-22 00:42:58

标签: python csv dictionary

我正在遍历一个csv文件,并检查一列是否作为字典中的键出现。

这是CSV文件中的示例行

833050,1,109,B147599,162560,0

我正在检查第五列是否是该词典中的键

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

我通过了这个字典。作为变种。以下代码中的mt_budgets

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}

我不确定为什么不把它当作钥匙,这是怎么回事?

谢谢!

1 个答案:

答案 0 :(得分:4)

{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