简体   繁体   中英

Comparing list to dictionary key error python

I am iterating through a list and comparing each element to 2 dictionaries. The list elements are keys in the dictionaries. Some elements are in the 2 dictionaries, some are in one, some are in none.

for i in range(0,len(mylist)-1):
    if mylist[i] == mydict[mylist[i]]:
        print 'in dict 1'
    elif mylist[i] == mydict2[mylist[i]]:
        print 'in dict 2'
    else: print 'not in dictionaries'

My problem is it isn't getting past the first elif statement. If it doesn't find the list element in the 2 dictionaries, it prints a key error. I can't understand it because I have another loop in another part of the code that's very similar to this and works perfectly. If a key isn't in a dictionary I want the else statement printed. Not a key error

Problem 1, as mgilson said, is that = is assignment, == is equality. However, even with your question edit, if you are looking to find out if a key is in a dictionary, you should be using the in operator, not the equals. In other words, the form if key in dict: . So:

for key in mylist:
    if key in mydict1:
        print 'Key %s in dict 1' % key
    elif key in mydict2:
        print 'Key %s in dict 2' % key
    else:
        print 'Key %s not in dictionaries' % key

You could abstract this further to handle an arbitrary set of dicts with a function, if that would prove helpful in the long run (though for a small number of dicts, like 2, you are probably better of with the above hardcoded checking):

def print_keys_from_list_in_dicts(key_list, dict_list):
    indexed_dict_list = enumerate(dict_list)
    for key in key_list:
        found_in_list = []
        for index, dict in indexed_dict_list:
            if key in dict:
                found_in_list.append(index)
        print 'Key %s found in dicts %s.' % (key, found_in_list)

print_keys_from_list_in_dicts(mylist, [mydict1, mydict2])

You can check the keys in a dictionary like this:

if mylist[i] in mydict:

Also, if you have a list of 10 items, range(0,len(mylist)-1) will return [0,1,2,3,4,5,6,7,8] so the last element in your list will probably not be considered in any case.

You can use the get method for dictionaries.

if mylist[i] == mydict.get(mylist[i],nonsense_value):
   ...

if nonsense_value isn't given, it defaults to None which may be nonsense enough for your purposes. But, this doesn't really make sense as it checks if the dictionary value is the same as the key.

You probably just want to check if the key is in the dictionary, you should use this idiom:

if mylist[i] in mydict:
   print "in dict 1"
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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