简体   繁体   中英

How do I do this with Python list? (itemgetter?)

[{'id':44}, {'name':'alexa'},{'color':'blue'}]

I want to select whatever in the list that is "id". Basically, I want to print 44, since that's "id" in the list.

That's a weird data structure... A list of one item dictionaries.

key = 'id'
l = [{'id':44}, {'name':'alexa'},{'color':'blue'}]

print [ x[key] for x in l if key in x ][0]

Assuming you can rely on key being present precisely once...

Maybe you should just convert the list into a dictionary first:

key = 'id'
l = [{'id':44}, {'name':'alexa'},{'color':'blue'}]

d = {}
for x in l:
    d.update(x)
print d[key]

All the other answers solve your problem, I am just suggesting an alternative way of going about doing this.

Instead of having a list of dict s where you query on the key and have to iterate over all list items to get values, just use a dict of list s. Each key would map to a list of values (or just one value if all your dict s had distinct sets of keys).

So,

data=[{'id':44}, {'name':'alexa'},{'color':'blue'}]

becomes

data={'id':[44], 'name':['alexa'], 'color':['blue']}

and you can neatly access the value for 'id' using data['id'] (or data['id'][0] if you only need one value).

If all your keys are distinct across the dict s (as in your example) you don't even have to have list s of values.

data={'id':44, 'name':'alexa', 'color':'blue'}

Not only does this make your code cleaner, it also speeds up your queries which no longer have to iterate over a list .

You could do something like this:

>>> KEY = 'id'
>>>
>>> my_list = [{'id':44}, {'name':'alexa'},{'color':'blue'}]
>>> my_ids = [x[KEY] for x in my_list if KEY in x]
>>> print my_ids
[44]

Which is obviously a list of the values you want. You can then print them as required.

Probably this is the best solution:

>>> L = [{'id':44}, {'name':'alexa'},{'color':'blue'}]

>>> newd = {}
>>> for d in L:
...    newd.update(d)
>>> newd['id']
44
 >>> from itertools import dropwhile
 >>> def find_value(l, key):
 ...    return dropwhile(lambda x: key not in x, l).next()[key]
 >>> find_value([{'id':44}, {'name':'alexa'},{'color':'blue'}], "id")

This will do a linear search, but only until the element is found.

If you want to have proper error handling, use:

def find_value(l, key):
    try:
        return dropwhile(lambda x: key not in x, l).next()[key]
    except StopIteration:
        raise ValueError(key)
>>> L = [{'id':44}, {'name':'alexa'},{'color':'blue'}]
>>> newd=dict(d.items()[0] for d in L)
>>> newd['id']
44

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM