What's the way to keep the dictionary parameter order in Python?
def createNode(doc_, **param_): cache = {'p':'property','l':'label','td':'totalDelay','rd':'routeDelay','ld':'logicDelay'} for index in param_: newIndex = cache[index] value = param_[index] print newIndex, '=', valuedoc = 10 createNode(doc, p='path', l='ifft4k_radix4_noUnolling_开发者_JAVA技巧core.vi', td='3.0', ld='1.0', rd='2.0')
Running this code on Python 2.6 gives me the following result.
routeDelay = 2.0 property = path totalDelay = 3.0 logicDelay = 1.0 label = ifft4k_radix4_noUnolling_core.vi
I need to keep the order of the parameters, I mean, property
comes first, then label
until I get routeDelay
last.
Q : What's the way to keep the dictionary parameter order in Python?
I need to keep the order of the parameter, I mean, property comes first, then label until I get reouteDelay last.
Then you're simply doing things in the wrong order -- no need for ordered dictionaries! Try, instead, a tuple of pairs for cache, as follows:
def createNode(doc_, **param_):
cache = ( ('p', 'property'), , ('l', 'label'), ('td', 'totalDelay'),
('rd', 'routeDelay'), ('ld', 'logicDelay') )
for index, newIndex in cache:
if index not in param_:
continue
value = param_[index]
print newIndex, '=', value
This has exactly the same semantics as your version of createNode
, plus the desired property of maintaining the order you wish, and performance is at least as good. By focusing on "keeping the dictionary ordered" you're focusing on the wrong problem (as is the case, alas, for most cases where people reach for "ordered dictionaries"!-).
A regular dictionary won't do, you'll have to use an ordered dictionary instead. Check out these links:
- PEP 372: Adding an ordered dictionary to collections
- Using an ordered dict as object dictionary in python -- an SO question to prove that people are using PEP 372's odict :-)
- Nicola Larosa & Michael Foord's odict module
Try the search term "python ordered dictionary" if you want to Google around for more. I remember seeing a number of ordered dict related questions here, on SO, so if the above links are inadequate for some reason, perhaps you can find something better in some other question.
Update: Mark's suggestion to use a list of tuples may be perfectly good, actually, but named tuples may be more convenient: a relevant fragment in the docs. Also, if you're planning to do some serialisation / deserialisation on your data and would like to do it really fast, check out Google's protocol buffers (Python tooling available).
Dictionaries don't preserve the order of the keys. You could use a list of tuples instead of a dictionary.
精彩评论