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

Trey Keown trey at opmstech.org
Sat Aug 25 03:56:32 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]
Okay, the reason I need to know this is that expat, my xml parsing module,
returns the attributes of an xml element as a dictionary. Now that i've
done what you recommended above, my xml parsing program returns the
dictionary's value as the value <i>and</i> the tag.
here's my code-
global window_attrs_key_order
window_attrs_key_order = ["name", "title", "icon"]
def start_element(name, attrs):
	global window_attrs_key_order
	if name in acceptedelements:
		if name == "window":
			print attrs.iteritems()
			for (tag,val) in attrs.iteritems():
				if tag in window_attrs_key_order:
					for tag in window_attrs_key_order:
						if tag == u"name":
							print "%s%s = Tk()" %(whitespace, val)
							print "***^^^%s^^^***" %val
							whatwindow = val
						if tag == u"title":
							print "%s%s.title(\"%s\")" % (whitespace, whatwindow, val)
						if tag == u"icon":
							if val == "NONE":
								print "#---->NO ICON"
								print "%s%s.iconbitmap(\"%s\")" %(whitespace, whatwindow, val)
					print "#-----Error, unrecognized attribute in window element...-----"

here's a likely example of what expat would spit out the attributes as-

attrs={u'title': u'example window title', u'name': u'SELF', u'icon':

and the program output is this-

<dictionary-itemiterator object at 0x0112F900>
Example Window Title = Tk()
***^^^Example Window Title^^^***
Example Window Title.title("Example Window Title")
Example Window Title.iconbitmap("Example Window Title")
SELF = Tk()
e.ico = Tk()

why would you think that the program would do this?

More information about the Tutor mailing list