<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta content="text/html;charset=ISO-8859-1" http-equiv="Content-Type">
<title></title>
</head>
<body bgcolor="#ffffff" text="#000000">
Thanks to Kent Johnson, Robert Berman, Bill Campbell and John Fouhy for
the replies.<br>
They have been useful.<br>
<br>
Kent Johnson wrote:
<blockquote
cite="mid:1c2a2c590809231918m68729826n3ac7ffe57320bf2@mail.gmail.com"
type="cite">
<pre wrap="">On Tue, Sep 23, 2008 at 8:41 PM, Joe Python <a class="moz-txt-link-rfc2396E" href="mailto:jopython@gmail.com"><jopython@gmail.com></a> wrote:
</pre>
<blockquote type="cite">
<pre wrap="">Hi Pythonistas,
I have a large dictionary of dictionary (50,000+ keys) which has a structure
as follows:
DoD = {
'flintstones' : {
'husband' : "fred",
'pal' : "barney",
'income' : 500,
},
'jetsons' : {
'husband' : "george",
'wife' : "jane",
'his boy' : "elroy",
'income' : 700,
},
'simpsons' : {
'husband' : "homer",
'wife' : "marge",
'kid' : "bart",
'income' : 600,
},
};
I want to sort the dictionary by 'income'
Is there an efficient way to do the same.
</pre>
</blockquote>
<pre wrap=""><!---->
As has been pointed out, you can't sort a dictionary, it is unordered.
You can sort the list of key, value pairs. The simplest way is to make
a key function that extracts the value on which to sort.
The key, value pairs will look like ('flintstones', {
'husband' : "fred",
'pal' : "barney",
'income' : 500,
)
You want to sort on the 'income' element of the value; this key
function will work:
def key(item):
return item[1]['income']
Then sort with
sorted(DoD.iteritems(), key=key)
Kent
</pre>
</blockquote>
<br>
</body>
</html>