Reputation: 971
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?
Upvotes: 1
Views: 328
Reputation: 8036
Dictionaries in python (and hash tables in general) are unordered. In python you can use the sort()
method on the keys to sort them.
Upvotes: 16
Reputation: 304215
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
Upvotes: 5
Reputation: 36832
Dictionaries have no intrinsic order. You'll have to either roll your own ordered dict implementation, use an ordered list
of tuple
s or use an existing ordered dict
implementation.
Upvotes: 5
Reputation: 304215
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')]
>>>
Upvotes: 2
Reputation: 13001
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']
Upvotes: 0
Reputation: 96736
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.
Upvotes: 0