1

I want to search an array if it contains an variable "Foo"

details={u'firstName': u'Test', u'activeSubscriptions': [{u'productCode': u'BBB', u'name': u'Bar'}, {u'productCode': u'FFF', u'name': u'Foo'}

I have done like this:

subscriptions_name = data['activeSubscriptions'][0]['name']

but this only works for the first data in the array.

How could I get the name of FFF if the data is not placed consistently?

2
  • Does it have to be FFF or do you want to check value of name for all dicts in activeSubscriptions? Commented Sep 2, 2014 at 7:56
  • Note that it is not an array but a dict. Commented Sep 23, 2014 at 4:41

3 Answers 3

1

If you are searching by productCode in your activeSubscriptions array, you are looking for this:

>>> details={'firstName': 'Test', 'activeSubscriptions': [{'productCode': 'BBB', 'name': 'Bar'}, {'productCode': 'FFF', 'name': 'Foo'}]}
>>> product_code_search_key = 'FFF'
>>> for subscription in details['activeSubscriptions']:        
...     if subscription and subscription.get('productCode','') and subscription['productCode'] == product_code_search_key:
...         print subscription['name']
...         break
... 
>>> Foo
Sign up to request clarification or add additional context in comments.

Comments

0

you can iterate the array of dictonary and acheive like below

details={'firstName': 'Test', 'activeSubscriptions': [{'productCode': 'BBB', 'name': 'Bar'}, {'productCode': 'FFF', 'name': 'Foo'}]}

for i in details['activeSubscriptions']:        
    if 'Foo' in i.values():
        print i

Comments

0

You can flatten your list recursively and search inside it:

def flatten(l):
    res = []
    for e in l:
        if type(e) is dict:
            tmp = e.values()
            res += flatten(tmp)
         elif type(e) is list:
             tmp = e[:]
             res += flatten(tmp)
         else:
             res += e
    return res

if "Foo" in flatten(list)

Edit: for performance reason, it is unnecessary to compute the array and search inside it. Following a version that just search inside the array:

def is_in_superlist(l, m):
    for e in l:
        if type(e) is dict:
            return is_in_superlist(e.values(), m)
         elif type(e) is list:
             return is_in_superlist(e, m)
         else:
             if e == m:
                 return True
    return False

is_in_superlist(list, "Foo")             

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.