0

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'

  • Possible duplicate of [Python and no obvious way to get a specific element from a dictionary](http://stackoverflow.com/questions/6701449/python-and-no-obvious-way-to-get-a-specific-element-from-a-dictionary) – ste-fu Jan 28 '16 at 08:37

3 Answers3

2

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
Pynchia
  • 10,996
  • 5
  • 34
  • 43
1

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
ellaRT
  • 1,346
  • 2
  • 16
  • 39
0

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
vks
  • 67,027
  • 10
  • 91
  • 124