NSP
NSP

Reputation: 1243

How to find a particular key in list of dictionary objects in python

i have query.oderby which is a list of dict objects.

[{'name': 'asc'}, {'user_id': 'desc'}]

I check if the list has user_id with the following

for query in query.orderby:
    if query.keys().__contains__('user_id'):
        if query['user_id'] == 'desc':
            #then sort in desc order
        elif query['user_id'] == 'asc':
            #the sort in asc order
        else:
            #move to next dict object
            query = query + 1

    else:
        #do something else if no user_id found in the list of dict

How can i check for user_id otherwise without using contains() and using the for loop? I tried

if query.keys() == 'user_id':
    #then do something

But this didn't help.

Upvotes: 0

Views: 1642

Answers (3)

DineshKumar
DineshKumar

Reputation: 1739

You may use something like this if u want ur code to look simple.

l = [{'name': 'asc'}, {'user_id': 'desc'}]

for query in l:
   if (query.has_key('user_id')):
       print "Key Found"

Upvotes: 0

SuperNova
SuperNova

Reputation: 27466

without for loop..

any(map((lambda x: True if 'user_id' in x.keys() else False ), ar ))

Upvotes: 0

3kt
3kt

Reputation: 2553

You can do this :

>>> ar = [{'name': 'asc'}, {'user_id': 'desc'}]
>>> any('user_id' in elt for elt in ar)
True

You can find more informations regarding any() here.

Hope it'll be helpful.

Upvotes: 2

Related Questions