OrderedDict在双迭代器循环后改变顺序

时间:2016-06-13 14:14:31

标签: python python-2.7 ordereddictionary

我设置ACK并使用不同的语法执行字典理解,我已将其简化为函数OrderedDict

dictcomp(fn, dictionary, key_or_value):

此时我可以对字典进行排序:

    x = OrderedDict(self._Median_Colors)
    x = self.dictcomp(hex2color, x, 'v')
    x = self.dictcomp(rgb_to_hsv, x, 'v_tuple')

到目前为止,一切似乎都要检查出来:

    x = self.dictcomp(self.sort_by_hue, x, 'v')

现在我需要重命名密钥,因此我将创建一个新的有序字典:

    print x

我不知道如何立即填写旧值,所以我这样做了:

    color_indexes = list(xrange(0, len(x.keys())))
    print color_indexes

    newkeys = [self.rename(color_index) for color_index in color_indexes]

    print x.values()
    vi = iter(x.values())
    x = OrderedDict.fromkeys(newkeys);

退房罚款:

    ki = iter(x.keys())
    for k, v in zip(ki, vi):
        #print "k:", k
        print  v
        x[k] = tuple(v)

遇到麻烦:

    print x.items()

其中dictcomp执行此操作:

    x = self.dictcomp(hsv_to_rgb, x, 'v_tuple')
    print x.items()

其中 dictionary = {k: fn(*v) for k, v in dictionary.items()} fn=hsv_to_rgb

现在,我有:

dictionary=x

而不是预期的:

[('Blue', (0.9764705882352941, 0.5529411764705883, 0.0)), ....

键是相同的,但值已更改。我猜测插入顺序以某种方式受到影响。这是怎么发生的?如何保持字典中键的顺序?

1 个答案:

答案 0 :(得分:0)

问题是因为

for i, j in zip([4, 5, 6], [1, 2, 3]):
    print i
    print j

列中的结果:

4 1 5 2 6 3

事实证明,如果使用两个迭代器,zip就像拉链一样。

修复方法是将关键字值作为可迭代元组:

for i in zip([4, 5, 6], [1, 2, 3]):
    print i

返回

(4, 1)
(5, 2)
(6, 3)