python - A way to gaurantee ordering of key/value list from unordered dictionary? -


i have dictionary, contains title , data. there way split data 2 lists while keeping order extracted dictionary? have process key list , value list separately, , use lists build string.

it's important because print them out separately, , output has match. doesn't matter if lists out of order when entered. long positions match in lists, it's fine.

here simple example represent case:

mydict = {'hello':1, 'world':2, 'again':3} keys = mydict.keys() values = mydict.values()  print 'the list of keys are: %s' % stringify(keys) print 'the corresponding values are: %s' % stringify(values)  # output: > list of keys are: hello, again, world > corresponding values are: 1, 3, 2 

i know can build ordered dictionary , getting key/value ordering guaranteed, handle case (non-ordered dictionary).

even though order see pairs in arbitrary, output keys() , values() will align, assuming don't modify dictionary. docs:

if items(), keys(), values(), iteritems(), iterkeys(), , itervalues() called no intervening modifications dictionary, lists directly correspond. allows creation of (value, key) pairs using zip(): pairs = zip(d.values(), d.keys()). same relationship holds iterkeys() , itervalues() methods: pairs = zip(d.itervalues(), d.iterkeys()) provides same value pairs. way create same list pairs = [(v, k) (k, v) in d.iteritems()].


Comments

Popular posts from this blog

php - Calling a template part from a post -

Firefox SVG shape not printing when it has stroke -

How to mention the localhost in android -