【发布时间】:2016-06-13 14:14:31
【问题描述】:
我设置了一个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()
麻烦来了:
x = self.dictcomp(hsv_to_rgb, x, 'v_tuple')
print x.items()
dictcomp 在哪里这样做:
dictionary = {k: fn(*v) for k, v in dictionary.items()}
在哪里fn=hsv_to_rgb,dictionary=x
现在,我有:
[('Blue', (0.9764705882352941, 0.5529411764705883, 0.0)), ....
而不是预期的:
[('Red', (0.4745098039215686, 0.7372549019607844, 0.23137254901960794)), ....
键相同,但值已更改。我猜插入顺序受到了某种影响。这是怎么发生的?如何保持字典中键的顺序?
【问题讨论】:
标签: python python-2.7 ordereddictionary