views:

206

answers:

6

Why dictionaries in python appears reversed?

>>> a = {'one': '1', 'two': '2', 'three': '3', 'four': '4'}
>>> a
{'four': '4', 'three': '3', 'two': '2', 'one': '1'}

How can I fix this?

+15  A: 

Dictionaries in python (and hash tables in general) are unordered. In python you can use the sort() method on the keys to sort them.

Kyle Lutz
Ok, I'll use keys/values
myfreeweb
A: 

And what is the "standard order" you would be expecting? It is very much application dependent. A python dictionary doesn't guarantee key ordering anyways.

In any case, you can iterate over a dictionary keys() the way you want.

jldupont
+5  A: 

Dictionaries have no intrinsic order. You'll have to either roll your own ordered dict implementation, use an ordered list of tuples or use an existing ordered dict implementation.

voyager
404. broken link!
myfreeweb
@myfreeweb: there are two links, and I can access them both http://www.voidspace.org.uk/python/odict.html http://code.activestate.com/recipes/107747/
voyager
+2  A: 

Now you know dicts are unordered, here is how to convert them to a list which you can order

>>> a = {'one': '1', 'two': '2', 'three': '3', 'four': '4'}
>>> a
{'four': '4', 'three': '3', 'two': '2', 'one': '1'}

sorted by key

>>> sorted(a.items())
[('four', '4'), ('one', '1'), ('three', '3'), ('two', '2')]

sorted by value

>>> from operator import itemgetter
>>> sorted(a.items(),key=itemgetter(1))
[('one', '1'), ('two', '2'), ('three', '3'), ('four', '4')]
>>> 
gnibbler
A: 

From the Python Tutorial:

It is best to think of a dictionary as an unordered set of key: value pairs

And from the Python Standard Library (about dict.items):

CPython implementation detail: Keys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary’s history of insertions and deletions.

So if you need to process the dict in a certain order, sort the keys or values, e.g.:

>>> sorted(a.keys())
['four', 'one', 'three', 'two']
>>> sorted(a.values())
['1', '2', '3', '4']
Mark van Lent
+5  A: 

Python3.1 has an OrderedDict

>>> from collections import OrderedDict
>>> o=OrderedDict([('one', '1'), ('two', '2'), ('three', '3'), ('four', '4')])
>>> o
OrderedDict([('one', '1'), ('two', '2'), ('three', '3'), ('four', '4')])
>>> for k,v in o.items():
...  print (k,v)
... 
one 1
two 2
three 3
four 4
gnibbler
Awesome. But I've done this without ordered dicts on Python 2.
myfreeweb