How to sort a Python dict (dictionary) by keys or values
How to sort a dict by keys (Python 2.4 or greater):
mydict = {'carl':40,
'alan':2,
'bob':1,
'danny':3}
for key in sorted(mydict.iterkeys()):
print "%s: %s" % (key, mydict[key])
alan: 2 bob: 1 carl: 40 danny: 3
Taken from the Python FAQ:
http://www.python.org/doc/faq/general/#why-doesn-t-list-sort-return-the-sorted-list. To sort the keys in reverse, add reverse=True as a keyword argument
to the sorted function.
How to sort a dict by keys (Python older than 2.4):
keylist = mydict.keys()
keylist.sort()
for key in keylist:
print "%s: %s" % (key, mydict[key])
The results are the same as the above.
How to sort a dict by value (Python 2.4 or greater):
for key, value in sorted(mydict.iteritems(), key=lambda (k,v): (v,k)):
print "%s: %s" % (key, value)
bob: 1 alan: 2 danny: 3 carl: 40Taken from Nick Galbreath's Digital Sanitation Engineering blog article
See also:
- The documentation for
sortedin 2.1 Built-in Functions and the.sort()method in 3.6.4 Mutable Sequence Types in the Python Library Reference. - Sorting Dictionaries by Value in Python (improved?) by Gregg Lind August 30, 2008
Related posts
- How to sort a list of dicts in Python — posted 2010-04-02
- Python setdefault example — posted 2010-02-09
- How to conditionally replace items in a list — posted 2008-08-22
- How to use Python's enumerate and zip to iterate over two lists and their indices. — posted 2008-04-18
- How to invert a dict in Python — posted 2008-01-14
- How to find the intersection and union of two lists in Python — posted 2008-01-03
10
Comments
—
Comments feed for this post
#4 Gregg Lind commented on 2008-09-12:
Thanks for the link to my article. If you need faster dictionary sorting than the ones you describe, it has some tips, as Nick's updated blog also shows.
#5 Eliot commented on 2008-09-12:
Gregg, Good work-- your article shows that you have obviously explored this topic much more thoroughly than I have. I will definitely try your method the next chance I get.
#7 gcd0318 commented on 2011-02-15:
are you sure this works? please see my result (I did in python shell):
>>> d={80: '0101', 75: '1011', 85: '0001', 70: '1111'}
>>> d
{80: '0101', 75: '1011', 85: '0001', 70: '1111'}
>>> kl=list(d.keys())
>>> kl
[80, 75, 85, 70]
>>> new_kl = kl + []
>>> new_kl
[80, 75, 85, 70]
>>> new_kl.sort()
>>> new_kl
[70, 75, 80, 85]
>>> new_d = {}
>>> for k in new_kl:
new_d[k] = d[k]
print(new_d)
{70: '1111'}
{75: '1011', 70: '1111'}
{80: '0101', 75: '1011', 70: '1111'}
{80: '0101', 75: '1011', 85: '0001', 70: '1111'}
>>> new_d
{80: '0101', 75: '1011', 85: '0001', 70: '1111'}
>>>
#8 Eliot commented on 2011-03-28:
gcd0318:
The items in a dict are stored in an undefined order. Printing the dict only confirms this fact.
If you need to operate on items in a dict in a sorted order, you can operate on each item within the for loop.
Or you can use a data structure that preserves order such as a list or the new OrderedDict data structure in the collections module added in Python 2.7. See http://docs.python.org/library/collections.html#collections.OrderedDict
#9 ovi commented on 2011-08-04:
Can someone explain the following behavior:
DICT = {'C':'C','G':'G','S':'S','E':'E','GE':'GE','fRrc':'GE','fAct':'FO'}
print DICT {'C': 'C', 'E': 'E', 'G': 'G', 'S': 'S', 'fRrc': 'GE', 'GE': 'GE', 'fAct': 'FO'}
Why is the order of the elements in the dictionary changed?
In fact, from what I've understood, there is no defined order about how the elements are stored.
So, the question is ... there is such a structure in python? (I don't want the dictionary to be sorted, I just want to preserve the order how they were initially added).
Thanks
Post a comment
About
I'm Eliot and this is my notepad for programming topics such as Python, Django, Ubuntu, Emacs, etc... more »
Search Blog
Tags
-
algorithms
(5)
-
aws
(9)
-
blogproject
(20)
-
c_cplusplus
(12)
-
cardstore
(8)
-
colinux
(2)
-
concurrency
(13)
-
conkeror
(2)
-
core
(2)
-
cygwin
(17)
-
datastructures
(14)
-
datetime
(4)
-
decorators
(4)
-
django
(40)
-
emacs
(22)
-
files_directories
(11)
-
git
(5)
-
hardware
(5)
-
install_setup
(8)
-
javascript
(3)
-
keyboard
(9)
-
matplotlib
(5)
-
mercurial
(4)
-
nginx
(2)
-
persistence
(5)
-
preferences
(7)
-
processes
(4)
-
pyqt
(18)
-
python
(144)
-
ratpoison
(3)
-
regexes
(6)
-
rsync
(3)
-
softwaretools
(17)
-
sql
(14)
-
ssh
(10)
-
subversion
(6)
-
twisted
(7)
-
ubuntu
(65)
-
urxvt
(5)
-
vxworks
(25)
-
webdev
(5)
-
wmii
(7)
Blogroll
- Adam Gomaa
- Alex Clemesha
- Amir Salihefendic
- Armin Ronacher
- David Beazley
- David Ziegler
- Duncan McGreggor
- Gareth Rushgrave
- Glyph Lefkowitz
- Guido van Rossum
- Ian Bicking
- Jacob Kaplan-Moss
- James Bennett
- James Tauber
- Jesper Noehr
- Marty Alchin
- Matt Harrison
- Nikolay Kolev
- Parand Darugar
- Peter Baumgartner
- Peter Bengtsson
- Rob Hudson
- Simon Willison
- Will McGugan
#1 Marius commented on 2007-11-30:
Thank you.