000
000

Reputation: 99

Searching for a key in python dictionary using "If key in dict:" seemingly not working

I'm iterating through a csv file and checking whether a column is present as a key in a dictionary.

This is an example row in the CSV file

833050,1,109,B147599,162560,0

I'm checking whether the 5th column is a key in this dictionary

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

I pass in this dict. as the var. mt_budgets in the following code

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

This is the output I'm getting

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

I'm not sure why it's not picking it up as a key, what's going on here?

Thanks!

Upvotes: 0

Views: 61

Answers (1)

user10356004
user10356004

Reputation:

{162560: True} # {int:bool}
{'162560': True} # {str:bool}

So, mt_budgets does not contain '162560' (str), it contains 162560 (int)

Your code should be:

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

Upvotes: 4

Related Questions