views:

87

answers:

4

I have a following dictionary :
{2009: [12, 11, 10, 9], 2010: [1]}

I'm trying to reverse-sort it, so that 2010 comes first. Here's the code :

def dictSort(dict):
    items = dict.items()
    items.sort(reverse=True)
    dict = {}
    for item in items:
        dict[item[0]] = item[1]
    return dict

But in return I get the same dictionary. Until the for loop everything looks fine. Why is that ?

+2  A: 

A dictionary is unordered, whatever you put into it isn't stored in the order you add to it.

If you want to do something to it in sorted order, you can do:

items = dict.items.sort(reverse=True)
for item in items:
    doSomething(item,mydict[item])

or

for key,value in iter(sorted(mydict.iteritems(),reverse=True))
     doSomething(key,value)
nos
dict.items is a function, not an attribute; sort works in-place, so you cannot assing its output (which is None). Maybe for item in sorted(mydict.items()): ...
tokland
+2  A: 

Dictionary keys are not ordered. Think of a dict as a set of key/value pairs.

This is coming in Python 3.1: http://docs.python.org/dev/library/collections.html#collections.OrderedDict

dkamins
Note: `OrderedDict` is in Python 2.7 too. (Earlier versions can use a [recipe](http://code.activestate.com/recipes/576693/)).
Piet Delport
@Piet - Very cool!
dkamins
A: 

Dictionaries don't have an order. If you are trying to output the dictionary in a certain order, try grabbing all the keys, sorting them, and using that list to know which order to output things.

Kevin Wiskia
A: 

Here one way to generate items of dict in reversed order of key (BTW please do not use dict for variable name!):

def dict_sort(thisdict, reverse=True):
    return ((key, thisdict[key]) for key in sorted(thisdict, reverse=reverse))

mydict = {2009: [12, 11, 10, 9], 2010: [1]}
for i in dict_sort(mydict):
    print "%i: %s" % i
Tony Veijalainen