ordereddictionary - Python OrderedDict iteration -
why python ordereddict initialized 'out of order'?
the solution here less intriguing explanation. there's here don't get, , perhaps expanation others me.
>>> collections import ordereddict >>> spam = ordereddict(s = (1, 2), p = (3, 4), = (5, 6), m = (7, 8)) >>> spam ordereddict([('a', (5, 6)), ('p', (3, 4)), ('s', (1, 2)), ('m', (7, 8))]) >>> key in spam.keys(): ... print key ... # 'ordered' not order wanted.... p s m # expecting (and wanting): s p m
from the docs:
the ordereddict constructor ,
update()
method both accept keyword arguments, order lost because python’s function call semantics pass-in keyword arguments using regular unordered dictionary.
so initialization loses ordering, because it's calling constructor **kwargs
.
edit: in terms of solution (not explanation)—as pointed out in comment op, passing in single list of tuples will work:
>>> collections import ordereddict >>> spam = ordereddict([('s',(1,2)),('p',(3,4)),('a',(5,6)),('m',(7,8))]) >>> key in spam: ... print(key) ... s p m >>> key in spam.keys(): ... print(key) ... s p m
this because it's getting single argument, list.
Comments
Post a Comment