首页 > 解决方案 > 将长列表/数组放入以索引为键的字典中

问题描述

我正在尝试解决编码练习。其中一部分是从随机整数列表中创建字典。字典必须具有作为key原始列表中元素的索引和作为列表value的元素。

这是我的功能:

def my_funct(pricesLst):
    price_dict = {}
    for i in range(0, len(pricesLst)):
        price_dict[i] = pricesLst[i]

    print(price_dict)


a = np.random.randint(1,100,5)

my_funct(a)

我得到的输出是正确的:

{0: 42, 1: 23, 2: 38, 3: 27, 4: 61}

但是,如果列表更长,我会得到一个奇怪的结果作为输出。

例子:

a = np.random.randint(1,1000000000,5000000)
my_funct(a)

输出是:

{2960342: 133712726, 2960343: 58347003, 2960344: 340350742, 949475: 944928187.........4999982: 417669027, 4999983: 650062265, 4999984: 656764316, 4999985: 32618345, 4999986: 213384749, 4999987: 383964739, 4999988: 229138815, 4999989: 203341047, 4999990: 54928779, 4999991: 139476448, 4999992: 244547714, 4999993: 790982769, 4999994: 298507070, 4999995: 715927973, 4999996: 365280953, 4999997: 543382916, 4999998: 532161768, 4999999: 598932697}

我不确定它为什么会发生。为什么我的字典的键不是从 0 开始,因为它发生在最短的列表中?

我唯一能想到的是列表太长,因此python,而不是使用从0开始的索引作为键,而是将内存中的空间关联起来。

标签: pythonnumpy

解决方案


因为python中的dicts不一定是有序的。您应该使用声明为的有序字典:

my_ordered_dict=OrderedDict()

推荐阅读