Sort dictionary

M

Markus Franz

Hi!

I have:

x = {'a':3, 'b':2, 'c':4}

How can I sort x by value? (I tried using sorted() with x.items() - but I
didn't get a dictionary as response.)

My second question:
How can I reduce the dictionary to 2 items (so delete everything after the
first two items)

Thanks in advance.

Best regards,
Markus
 
C

Claudio Grondi

Markus said:
Hi!

I have:

x = {'a':3, 'b':2, 'c':4}

How can I sort x by value? (I tried using sorted() with x.items() - but I
didn't get a dictionary as response.)

My second question:
How can I reduce the dictionary to 2 items (so delete everything after the
first two items)

Thanks in advance.

Best regards,
Markus

See my reply in de.comp.lang.python

Claudio
 
?

=?iso-8859-1?q?Luis_M._Gonz=E1lez?=

You can't get a dictionary ordered by values, but you can get a list of
key-value pairs ordered by value:

def sortByValue(myDict):
x = sorted( [(v,k) for k,v in myDict.items()] )
return [(k,v) for v,k in x]

For getting only the first two pairs:

sortByValue(x)[:2]

Hope this helps...
Luis
 

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
474,275
Messages
2,571,381
Members
48,070
Latest member
nick_tyson

Latest Threads

Top