0

I want to iterate through the keys of a dictionary which is sorted with values. one method is to use ordered dictionary means initialize dictionary with sorted values.

code:

from collections import OrderedDict

data = OrderedDict([('a',0), ('d',1), ('c',2), ('b',3)])

for mykey in data:
    print mykey

How can i achieve this without using Ordered dictionary ? I know that above was correct method to achieve this, i just want to know can we do the same without using Ordered dictionary.

sorted(dictionary.values) 

will give me only sorted list of values not whole dictionary with sorted values so i can't have keys here.

hivert
  • 10,579
  • 3
  • 31
  • 56
Patrick
  • 2,464
  • 3
  • 30
  • 47
  • possible duplicate of [How do I iterate over a Python dictionary, ordered by values?](http://stackoverflow.com/questions/674509/how-do-i-iterate-over-a-python-dictionary-ordered-by-values) – idanshmu Mar 05 '14 at 10:17

2 Answers2

1

Use dict.iteritems to get list of tuples from dict and sort it with sorted:

sorted(dictionary.iteritems(), key=lambda i: i[1])

from python docs about key argument:

key specifies a function of one argument that is used to extract a comparison key from each list element: key=str.lower. The default value is None (compare the elements directly).

ndpu
  • 22,225
  • 6
  • 54
  • 69
1

You could adapt the code in this answer to another question to obtain a relatively simple, yet fast, implementation, as shown:

class ValueOrderedDict(object):
    def __init__(self):
        self.d = {}
        self.L = []
        self.sorted = True
    def __getitem__(self, k):
        return self.d[k]
    def __setitem__(self, k, v):
        if k not in self.d:
            self.L.append((v, k))
            self.sorted = False
        self.d[k] = v
    def __delitem__(self, k):
        v = self.d[k]
        del self.d[k]
        self.L.remove((v, k))
    def __iter__(self):
       if not self.sorted:
           self.L.sort()
           self.sorted = True
       for v, k in self.L:
           yield k

vod = ValueOrderedDict()
vod['a'] = 10
vod['b'] =  5
vod['c'] = 20

for k in vod:
    print 'vod[{!r}]: {}'.format(k, vod[k])

Output:

vod['b']: 5
vod['a']: 10
vod['c']: 20
Community
  • 1
  • 1
martineau
  • 119,623
  • 25
  • 170
  • 301