在 Python 中保持字典参数顺序的方法是什么? [英] 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'}对于 param_ 中的索引:newIndex = 缓存[索引]值 = param_[索引]打印 newIndex, '=', valuedef 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, '=', value文档 = 10createNode(doc, p='path', l='ifft4k_radix4_noUnolling_core.vi', td='3.0', ld='1.0', rd='2.0')
doc = 10 createNode(doc, p='path', l='ifft4k_radix4_noUnolling_core.vi', td='3.0', ld='1.0', rd='2.0')
在 Python 2.6 上运行此代码会得到以下结果.
Running this code on Python 2.6 gives me the following result.
路由延迟 = 2.0属性 = 路径总延迟 = 3.0逻辑延迟 = 1.0标签 = ifft4k_radix4_noUnolling_core.virouteDelay = 2.0 property = path totalDelay = 3.0 logicDelay = 1.0 label = ifft4k_radix4_noUnolling_core.vi我需要保持参数的顺序,我的意思是,
property
先出现,然后是label
,直到最后得到routeDelay
.I need to keep the order of the parameters, I mean,
property
comes first, thenlabel
until I getrouteDelay
last.问:在 Python 中保持字典参数顺序的方法是什么?
Q : What's the way to keep the dictionary parameter order in Python?
推荐答案
我需要保持顺序参数,我的意思是,属性来了首先,然后标记直到我得到reouteDelay 最后一次.
I need to keep the order of the parameter, I mean, property comes first, then label until I get reouteDelay last.
那么你只是按照错误的顺序做事——不需要有序的字典!相反,尝试使用 cache 对的元组,如下所示:
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
这与您的
createNode
版本具有完全相同的语义,加上保持您希望的顺序的所需属性,并且性能至少一样好.通过专注于保持字典有序",您将注意力集中在错误的问题上(唉,对于大多数 情况,人们会找到有序字典"!-).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"!-).这篇关于在 Python 中保持字典参数顺序的方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!