我有一本(未排序的)字典,其中的键从0.0开始,然后以0.1、0.2、0.3等继续。所有的值也是数字。
我也有一个sys.argv输入,称为“ a”,它是一个浮点数。
我需要一本新字典,其中的键应为:

a
a+0.1
a+0.2
a+0.3


...,直到为原始字典中的所有值分配了键。值应保持不变。
所以最终的字典应该是:

{a:first item of sorted dict, a+0.1:second item of sorted dict,...}


因此,基本上,键应添加到浮点数“ a”的大小中。

我尝试通过将未排序的字典转换为如下的排序列表:

list=[]
for i in sorted(dict.keys()):
list.append(dict[i])


现在,我有了需要分配给新键的原始字典值的排序列表。

最佳答案

使用OrderedDict将增量映射到键和值:

>>> from collections import OrderedDict
>>> d = {0.1:1,0.2:2}
>>> d
{0.2: 2, 0.1: 1}
>>> od = OrderedDict(d)
>>> od
OrderedDict([(0.2, 2), (0.1, 1)])
>>> newOrderedDict = OrderedDict(map(lambda (x,y): (x+5, y), od.items()))
>>> newOrderedDict
OrderedDict([(5.2, 2), (5.1, 1)])


请注意,orderedDict会保持插入顺序而不是值顺序,因此,如果要让值顺序仅在构建新orderedDict之前对映射列表进行排序

>>> newOrderedDict = OrderedDict(sorted(map(lambda (x,y): (x+5, y), od.items()), key=lambda (x,y):x))
>>> newOrderedDict
OrderedDict([(5.1, 1), (5.2, 2)])

09-10 08:45
查看更多