Define key in nlargest() of heapq?

D

Davy

Hi all,

I have a dictionary with n elements, and I want to get the m(m<=n)
keys with the largest values.

For example, I have dic that includes n=4 elements, I want m=2 keys
have the largest values)
dic = {0:4,3:1,5:2,7:8}
So, the the largest values are [8,4], so the keys are [7,0].

How to do this by nlargest() of heapq? I have tried
nlargest(2,dic,key),
the interpreter give out:
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
NameError: name 'key' is not defined

Best regards,
Davy
 
R

Raymond Hettinger

I have a dictionary with n elements, and I want to get the m(m<=n)
keys with the largest values.

For example, I have dic that includes n=4 elements, I want m=2 keys
have the largest values)
dic = {0:4,3:1,5:2,7:8}
So, the the largest values are [8,4], so the keys are [7,0].

How to do this by nlargest() of heapq? I have tried
nlargest(2,dic,key),

Try this:
[7, 0]


Raymond
 
D

Davy

Hi Raymond,

Your code work well, thank you :)

Best regards,
Davy

I have a dictionary with n elements, and I want to get the m(m<=n)
keys with the largest values.
For example, I have dic that includes n=4 elements, I want m=2 keys
have the largest values)
dic = {0:4,3:1,5:2,7:8}
So, the the largest values are [8,4], so the keys are [7,0].
How to do this by nlargest() of heapq? I have tried
nlargest(2,dic,key),

Try this:

[7, 0]

Raymond
 
D

Duncan Booth

Davy said:
Hi all,

I have a dictionary with n elements, and I want to get the m(m<=n)
keys with the largest values.

For example, I have dic that includes n=4 elements, I want m=2 keys
have the largest values)
dic = {0:4,3:1,5:2,7:8}
So, the the largest values are [8,4], so the keys are [7,0].

How to do this by nlargest() of heapq? I have tried
nlargest(2,dic,key),
the interpreter give out:
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
NameError: name 'key' is not defined

Best regards,
Davy
You could use the code I posted for you yesterday. See message

http://groups.google.co.uk/group/co...78fa0?lnk=gst&q=duncan+booth#a605259c41c78fa0
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,065
Latest member
OrderGreenAcreCBD

Latest Threads

Top