使用Python的range()函数

时间:2015-05-23 22:37:51

标签: python dictionary

在Python 3.4中,运行代码

d = {}
for i in range(-100, 1): #exclusive endpoint
    d[i] = 0

应该为您提供一个字典d,该字典有100个以-100:0开头并以0:0开头的键/值对。但出于某种原因,每当我运行此代码时,我都会得到一个以键/值对0:0-1:0开头的字典,然后从-100:0转到-2:0

据我所知,我应该得到一本正确排序的字典,但出于某种原因,我不是。

我在这里做错了吗?或者Python中有什么时髦的东西?

proof

P.S:当我尝试从-100到100

制作字典时,它变得更加怪异

3 个答案:

答案 0 :(得分:4)

字典未在python

中排序

答案 1 :(得分:4)

dicts no order ,添加密钥的顺序无关紧要。

如果您想要订单,请使用colletions.OrderedDict维护广告订单:

from collections import OrderedDict
od = OrderedDict().fromkeys(range(-100, 1),0) #exclusive endpoint
print(od)

输出:

OrderedDict([(-100, 0), (-99, 0), (-98, 0), (-97, 0), (-96, 0), (-95, 0), (-94, 0), (-93, 0), (-92, 0), (-91, 0), (-90, 0), (-89, 0), (-88, 0), (-87, 0), (-86, 0), (-85, 0), (-84, 0), (-83, 0), (-82, 0), (-81, 0), (-80, 0), (-79, 0), (-78, 0), (-77, 0), (-76, 0), (-75, 0), (-74, 0), (-73, 0), (-72, 0), (-71, 0), (-70, 0), (-69, 0), (-68, 0), (-67, 0), (-66, 0), (-65, 0), (-64, 0), (-63, 0), (-62, 0), (-61, 0), (-60, 0), (-59, 0), (-58, 0), (-57, 0), (-56, 0), (-55, 0), (-54, 0), (-53, 0), (-52, 0), (-51, 0), (-50, 0), (-49, 0), (-48, 0), (-47, 0), (-46, 0), (-45, 0), (-44, 0), (-43, 0), (-42, 0), (-41, 0), (-40, 0), (-39, 0), (-38, 0), (-37, 0), (-36, 0), (-35, 0), (-34, 0), (-33, 0), (-32, 0), (-31, 0), (-30, 0), (-29, 0), (-28, 0), (-27, 0), (-26, 0), (-25, 0), (-24, 0), (-23, 0), (-22, 0), (-21, 0), (-20, 0), (-19, 0), (-18, 0), (-17, 0), (-16, 0), (-15, 0), (-14, 0), (-13, 0), (-12, 0), (-11, 0), (-10, 0), (-9, 0), (-8, 0), (-7, 0), (-6, 0), (-5, 0), (-4, 0), (-3, 0), (-2, 0), (-1, 0), (0, 0)])

你也可以使用词典理解来创建你的词典:

d = {k:0 for k in range(-100, 1)}

答案 2 :(得分:1)

for i in range(-100, 1)为您提供从-100到0(步数= 1)的数字范围。因此i从-100开始,每次迭代增加1(-99,98等)直到0.每次迭代你都要在字典中添加一个键,最后你的字典将包含一个100 < strong>无序键,从-100到0。

在python词典中总是无序的。如果你想要一个有序的字典,我建议你使用collection.OrderedDict,例如:

import collections

d = collections.OrderedDict()
for i in range(-100, 1):
    d[i] = 0