[Tutor] creating dictionary from a list

Steven D'Aprano steve at pearwood.info
Sun Apr 14 03:50:32 CEST 2013


On 14/04/13 04:19, Saad Javed wrote:

> This creates a dictionary whose keys are out of order in terms of dates.


Dictionaries are unordered. That is to say, they have no defined order, when
you print them, or iterate over them, items will appear in whatever order
they happen. If you modify a dict, the order can even change.

This is by design: access to items in the dict is extremely fast, especially
for large dicts, because Python doesn't have to search through the items one
at a time. Dicts are a type of "hash table", which is why dictionary keys must
be hashable.

(If you don't know what a hash table is, please ask.)

So you cannot rely on dicts being in any specific order.

There is an OrderedDict in the collections module which remembers the order
that items are inserted into the OrderedDict. But that's not quite the same
as items being sorted.


> {'Thu Apr 04': ['Weigh In'], 'Sat Apr 06': ['Collect NIC', 'Finish PTI
> Video'], 'Wed Apr 10': ['Serum uric acid test'], 'Sun Apr 14': ['Download
> Louis CK Oh My God', '4:00pm', 'UPS Guy'], 'Sat Apr 13': ['1:00pm', 'Get
> flag from dhariwal']}
>
> Sat Apr 13 is appearing after Sun Apr 14. How do you sort this?


You cannot sort a dictionary directly, but you can sort the keys, then iterate
over them in that order.

keys = sorted(mydict.keys())
for key in keys:
     print mydict[key]




-- 
Steven


More information about the Tutor mailing list