Two algorithms to sort a dictionary by it’s value
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
Posted by giovani |
[...] 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 | #