Reputation: 1447
I have the following in a dictionary:
"key": ["array_value1", "array_value2", "array_value3"],
I have another value I'd like to check against one of the values in the array in an if-else statement. For example:
if checkedValue == array_value1:
#something happens
I don't know how to iterative over the values in "key" so that it automatically checks for the values inside it.
Upvotes: 0
Views: 72
Reputation: 16499
Dictionary values have a type, just like anything else. It looks like your dictionary value in this case is an array, so iterate over it in the same way as you iterate over any other iterable collection:
for val in mydict["key"]:
if checkedValue == val:
doSomething
As pointed out in nickflees's answer, the array
type works well with the in
keyword, but this is just syntactic sugar for iterating through the array until you find the desired value. The point is that dictionary values are not "special" types in any way; mydict["key"]
is just a reference to whatever you've stored under that key in the dictionary.
Upvotes: 3
Reputation: 33360
Another way using any
.
for k, v in dy.iteritems():
if any(val == checkValue for val in v):
print "something happens"
For Python 3, use items
instead of iteritems
.
Upvotes: 1
Reputation: 1953
You could do something like
if checkedValue in dict_name['key']:
#do something
Upvotes: 3