Connecting Tech Pros Worldwide Help | Site Map

Sort dictionary

Markus Franz
Guest
 
Posts: n/a
#1: Jan 2 '06
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
Claudio Grondi
Guest
 
Posts: n/a
#2: Jan 2 '06

re: Sort dictionary


Markus Franz wrote:[color=blue]
> 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[/color]

See my reply in de.comp.lang.python

Claudio
Luis M. González
Guest
 
Posts: n/a
#3: Jan 2 '06

re: Sort dictionary


This function return a tuple of value-key pairs, sorted by value:
[color=blue][color=green][color=darkred]
>>> x = {'a':3, 'b':2, 'c':4}
>>> def sortByValue(myDict):[/color][/color][/color]
return sorted( [(v,k) for k,v in myDict.items()] )

If you want to get the first two value-key pairs:
[color=blue][color=green][color=darkred]
>>> sortByValue(x)[:2][/color][/color][/color]
[(2, 'b'), (3, 'a')]

Hope this helps...
Luis

Luis M. González
Guest
 
Posts: n/a
#4: Jan 2 '06

re: Sort dictionary


This function returns a tuple of value-key pairs, sorted by value:
[color=blue][color=green][color=darkred]
>>> x = {'a':3, 'b':2, 'c':4}
>>> def sortByValue(myDict):[/color][/color][/color]
return sorted( [(v,k) for k,v in myDict.items()] )

If you want to get the first two value-key pairs:[color=blue][color=green][color=darkred]
>>> sortByValue(x)[:2][/color][/color][/color]
[(2, 'b'), (3, 'a')]

Hope this helps...
Luis

Luis M. González
Guest
 
Posts: n/a
#5: Jan 3 '06

re: Sort dictionary


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

Closed Thread