[Tutor] Dict

Steven D'Aprano steve at pearwood.info
Tue Nov 26 13:07:17 CET 2013


On Tue, Nov 26, 2013 at 04:37:28PM +0530, Sunil Tech wrote:
> Hi Friends,
> 
> Is it possible to sort dict & to get result as dict?
> if it is possible, please give some example.

No it is not possible, dicts are deliberately unsorted.

Please read my explanation why from yesterday:

https://mail.python.org/pipermail/tutor/2013-November/098436.html

Instead, you can use an OrderedDict, which is ordered by insertion 
order, not sort order. But if you sort the items first, then insert them 
into the OrderedDict, it will be sorted.


py> from collections import OrderedDict
py> data = {'a':1, 'c':3, 'd':4, 'b':2}
py> items = sorted(data.items())
py> data = OrderedDict(items)
py> data
OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 4)])


Another solution is to only sort the items when you're ready to use 
them:

py> data = {'a':1, 'c':3, 'd':4, 'b':2}
py> for key in sorted(data.keys()):
...     print(key, data[key])
...
('a', 1)
('b', 2)
('c', 3)
('d', 4)


A third is to write your own SortedDict class. If you google for it, you 
will probably find dozens of ideas.


-- 
Steven


More information about the Tutor mailing list