Patrick
Patrick

Reputation: 2544

How to iterate through keys of a dictionary which is sorted with values?

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.

Upvotes: 0

Views: 150

Answers (2)

martineau
martineau

Reputation: 123453

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

Upvotes: 1

ndpu
ndpu

Reputation: 22561

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).

Upvotes: 1

Related Questions