ParTecs Weblog

Two algorithms to sort a dictionary by it’s value

February 27th, 2006

Here are 2 algorithms that I’ve use to sort dictionaries by their values. I have yet to profile both algorithms to see what works best in a senario. Personnally I feel the first method is more cognitive to Python developers.
Method 1 – Here I have converted the dictionary to a list of tuple (key, value) pairs. Further I have sorted the list by comparing the tuples second element.

>>> a = {1: 4, 2: 5, 4: 6, 7: 4} >>> sorted_dict = list(a.iteritems()) >>> sorted_dict.sort(lambda i1, i2: cmp(i1[1], i2[1])) >>> for key, value in sorted_dict: ... print key, value ... 1 4 7 4 2 5 4 6

Method 2 – In this case I have constructed a dictionary whose keys are the values of the dictionary I wanted sorted. The values of newly constructed dictionary is composed of a list of all the keys with the same value.

>>> for key, value in a.iteritems(): ... if sorted_dict.has_key(value): ... sorted_dict[value].append(key) ... continue ... sorted_dict[value] = [key] ... >>> for value, keys in sorted_dict.iteritems(): ... for key in keys: ... print key, value ... 1 4 7 4 2 5 4 6

1 Comment »

  1. Py! » Blog Archive » Listas y Diccionarios says

    […] Y ahora ordenar por valor, de ParTecs: for key, value in a.iteritems(): if sorted_dict.has_key(value): sorted_dict[value].append(key) continue sorted_dict[value] = [key] […]

    March 28th, 2006 | #

Leave a comment

:mrgreen: :neutral: :twisted: :shock: :smile: :???: :cool: :evil: :grin: :oops: :razz: :roll: :wink: :cry: :eek: :lol: :mad: :sad:

RSS feed for these comments. | TrackBack URI

Feedburner RSS

Enter your email address:

Delivered by FeedBurner

Blogroll

Categories

RSS Telematics Freedom

February 2006
M T W T F S S
    Mar »
 12345
6789101112
13141516171819
20212223242526
2728  

Archive

Sky Sponsored by Web Hosting