13

我有一本有序的字典,想更改个别的顺序。在下面的代码示例中,我希望项目 3(人)及其值移动到位置 2。因此顺序将是动物、人、食物、饮料。我该怎么处理他的?

import collections

queue = collections.OrderedDict()

queue["animals"] = ["cat", "dog", "fish"]
queue["food"] = ["cake", "cheese", "bread"]
queue["people"] = ["john", "henry", "mike"]
queue["drinks"] = ["water", "coke", "juice"]

print queue
4

4 回答 4

19

OrderedDicts插入顺序排序。因此,您必须通过遍历key:value原始对象中的对来构造一个新的 OrderedDict。没有任何OrderedDict方法可以帮助您。

因此,您可以创建一个tuple来表示 的想法顺序keys,然后对其进行迭代以创建一个新的OrderedDict.

key_order = ('animal', 'people', 'food', 'drink')
new_queue = OrderedDict()
for k in key_order:
    new_queue[k] = queue[k]

或者更有说服力

OrderedDict((k, queue[k]) for k in key_order)
于 2014-03-26T14:32:49.817 回答
6

编辑:您可以编写一个自定义函数(警告,这可行,但非常快速和肮脏):

编辑:修复了尝试前进时发生的错误

import collections

def move_element(odict, thekey, newpos):
    odict[thekey] = odict.pop(thekey)
    i = 0
    for key, value in odict.items():
        if key != thekey and i >= newpos:
            odict[key] = odict.pop(key)
        i += 1
    return odict

queue = collections.OrderedDict()

queue["animals"] = ["cat", "dog", "fish"]
queue["food"] = ["cake", "cheese", "bread"]
queue["people"] = ["john", "henry", "mike"]
queue["drinks"] = ["water", "coke", "juice"]
queue["cars"] = ["astra", "focus", "fiesta"]

print queue

queue = move_element(queue, "people", 1)

print queue
于 2014-03-26T14:40:37.137 回答
1

我认为您必须手动执行此操作:

>>> keys = list(queue)
>>> keys
['animals', 'food', 'people', 'drinks']
>>> keys[1], keys[2] = keys[2], keys[1]
>>> queue = collections.OrderedDict((key, queue[key]) for key in keys)
>>> list(queue)
['animals', 'people', 'food', 'drinks']
于 2014-03-26T14:33:44.013 回答
-1

看到这个问题。

如果不明确重新定义顺序,我认为您无法像希望的那样对字典进行排序。

于 2014-03-26T14:34:27.540 回答