Pluck in Python

Question:

I started reading about underscore.js today, it is a library for javascript that adds some functional programming goodies I’m used to using in Python. One pretty cool shorthand method is pluck.

Indeed in Python I often need to pluck out some specific attribute, and end up doing this:

users = [{
    "name" : "Bemmu",
    "uid" : "297200003"
},
{
    "name" : "Zuck",
    "uid" : "4"
}]
uids = map(lambda x:x["uid"], users)

If the underscore shorthand is somewhere in Python, this would be possible:

uids = pluck(users, "uid")

It’s of course trivial to add, but is that in Python somewhere already?

Asked By: Bemmu

||

Answers:

Just use a list comprehension in whatever function is consuming uids:

instead of

uids = map(operator.itemgetter("uid"), users)
foo(uids)

do

foo([x["uid"] for x in users])

If you just want uids to iterate over, you don’t need to make a list — use a generator instead. (Replace [] with ().)


For example:

def print_all(it):
    """ Trivial function."""
    for i in it:
        print i

print_all(x["uid"] for x in users)
Answered By: Katriel

From funcy module (https://github.com/Suor/funcy) you can pick pluck function.

In this case, provided that funcy is available on your host, the following code should work as expected:

from funcy import pluck

users = [{
    "name" : "Bemmu",
    "uid" : "297200003"
},
{
    "name" : "Zuck",
    "uid" : "4"
}]

uids = pluck("uid", users)

Pay attention to the fact that the order of arguments is different from that used with underscore.js

Answered By: Chaos Manor
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.