Need help with making use of Pluck in Python

0 votes

Hi all, today was a good day. I finally started researching on the underscore.js module today and I could find out a couple of stuff about it.
 

For one, it is a library which supports javascript. This basically adds to the functional aspects you get to work within Python as well. So this method is called pluck.

Now consider this - Let us say I have a requirement wherein I have to pluck out a specific attribute, this is what I'd do:

users = [{
    "name" : "Edureka",
    "uid" : "744639207"
},
{
    "name" : "Anirudh",
    "uid" : "3"
}]
uids = map(lambda x:x["uid"], users)

If the shorthand for the underscore is present somewhere in the same Python code, would the following piece of code be possible?

Code:

uids = pluck(users, "uid")

All help appreciated!

Jan 24 in Python by Anirudh
• 2,070 points
88 views

1 answer to this question.

0 votes

Hi, good question. Easy solution to be honest - Make sure you use of a list comprehension in all of the functions that make use and keep track of the uids.

Check out this following piece of code:

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

Instead of this piece of code, make use of this below code and it will solve the issue:

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

Let us say your only requirement is that you need the uids as an iteration variable, then make sure that you don't need a list. 

So what is the alternative? Use a generator. How do you do this?

It is very simple - Replace [] with () and you're good to go.

Hope this helped!

answered Jan 24 by Nymeria
• 3,520 points

Related Questions In Python

+2 votes
3 answers

what is the practical use of polymorphism in Python?

Polymorphism is the ability to present the ...READ MORE

answered Mar 31, 2018 in Python by anto.trigg4
• 3,420 points
1,330 views
+4 votes
6 answers

Use of "continue" in python

The break statement is used to "break" ...READ MORE

answered Jul 16, 2018 in Python by Omkar
• 67,460 points
132 views
0 votes
1 answer

Need help writing a dataframe into a csv with the help of a loop

Using the following logic you can arrive ...READ MORE

answered Apr 17, 2018 in Python by anonymous
937 views
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Need help extracting a schema to make use for an avro file in Python

Hi, nice question. So what I daily use ...READ MORE

answered Jan 10 in Python by Nymeria
• 3,520 points
472 views
0 votes
1 answer