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: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):