sort values from dictionary of dictionaries python 2.4
Peter Otten
__peter__ at web.de
Mon Nov 9 09:27:28 EST 2009
J Wolfe wrote:
> I would like to sort this dictionary by the values of the inner
> dictionary ‘ob’ key.
Python's built-in dictionary is unsorted by design.
> mydict =
> {’WILW1′: {’fx’: ‘8.1′, ‘obtime’: ‘2009-11-07 06:45:00′, ‘ob’: ‘6.9′},
> ‘GRRW1′: {’fx’: ‘12.8′, ‘obtime’: ‘2009-11-07 04:15:00′, ‘ob’: ‘6.7′},
> ‘NASW1′: {’fx’: ‘6.8′, ‘obtime’: ‘2009-11-07 06:30:00′, ‘ob’: ‘7.1′}
> }
>
> In this case, this would become:
>
> mysorteddic =
> {’NASW1′: {’fx’: ‘6.8′, ‘obtime’: ‘2009-11-07 06:30:00′, ‘ob’: ‘7.1′},
> ‘WILW1′: {’fx’: ‘8.1′, ‘obtime’: ‘2009-11-07 06:45:00′, ‘ob’: ‘6.9′},
> ‘GRRW1′: {’fx’: ‘12.8′, ‘obtime’: ‘2009-11-07 04:15:00′, ‘ob’: ‘6.7′}
> }
>
> I have had no luck in trying to figure this out. I am restricted to
> using python 2.4.3.
>
> Any help would be appreciated!
You may be able to work around that limitation by putting the dict items
into a list and sort that:
>>> for item in sorted(mydict.items(), key=lambda (k, v): float(v["ob"]),
reverse=True):
... print item
...
('NASW1', {'fx': '6.8', 'obtime': '2009-11-07 06:30:00', 'ob': '7.1'})
('WILW1', {'fx': '8.1', 'obtime': '2009-11-07 06:45:00', 'ob': '6.9'})
('GRRW1', {'fx': '12.8', 'obtime': '2009-11-07 04:15:00', 'ob': '6.7'})
Peter
More information about the Python-list
mailing list