Reputation: 1
I am having trouble. This is my code, I would like to check if a specific value exist in the dictionary. This is my code. I think the logic is right but the syntax is not correct. Please help me. Thank you.
a = [
{'amount':200, 'currency':'php'},
{'amount':100, 'currency':'usd'}
]
result1 = 200 in a
result2 = 'php' in a
result = result1 and result2
print result
I am expecting to have a result of 'True'
Upvotes: 0
Views: 677
Reputation: 1366
Use iteritems to iterate thru dictionary gettings its keys and values
a = [
{'amount':200, 'currency':'php'},
{'amount':100, 'currency':'usd'}
]
for lst in a:
for k,v in lst.iteritems():
if 200 == v:
res1 = 'True'
if 'php' == v:
res2 = 'True'
print res1 and res
Upvotes: 1
Reputation: 11590
The line
result1 = 200 in a
looks for a list element with the value of 200
.
But your list elements are dictionaries. So your expectations are impossible to achieve as stated.
So, assuming your goal is to check a particular value is contained in any of the elements (i.e. dictionaries) of list a
, you should write
result1 = any(200 in el.values() for el in a)
result2 = any('php' in el.values() for el in a)
result = result1 and result2
print result
which produces
True
Upvotes: 2
Reputation: 67968
You can do something like
a = [
{'amount':200, 'currency':'php'},
{'amount':100, 'currency':'usd'}
]
for i in a:
if 200 in i.values():
result1=True
if "php" in i.values():
result2=True
result = result1 and result2
print result
Upvotes: 0