[Tutor] Read dictionary data in a specific order...

Alan Gauld alan.gauld at btinternet.com
Sat Aug 25 01:41:18 CEST 2007


"Trey Keown" <trey at opmstech.org> wrote

> I would like to know, how can I read (or sort) a dictionary in a 
> certain
> order?

Dictionaries are by design unsorted and indeed may even change
their order during their lifetime.

> attrs={u'title': u'example window title', u'name': u'SELF', u'icon':
> u'e.ico'}
> how could I get the data so that u'name' is read first, u'title' 
> second,
> and u'icon' third?

Normally you would sort the keys of the dictionary but since
your order is not a natural sort order then the easiest way is
probably to create a list of the keys you want in the order you
want them. Thus:

keys = ['name','title','icon']
for key in keys: print attrs[key]

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 




More information about the Tutor mailing list