HotelCalifornia
HotelCalifornia

Reputation: 316

Using Python's range() function

In Python 3.4, running the code

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

should give you a dictionary, d, that has 100 key/value pairs starting with -100:0 and ending with 0:0. But for some reason, whenever I run this code, I get a dictionary that starts with the key/value pairs 0:0 and -1:0, then goes from -100:0 to -2:0.

As far as I know, I should be getting a correctly ordered dictionary, but for some reason, I'm not.

Is there something I'm doing wrong here? Or is there something funky going on within Python?

proof

P.S: It gets even weirder when I try to make the dictionary from -100 to 100

Upvotes: 0

Views: 497

Answers (3)

Gio
Gio

Reputation: 3340

for i in range(-100, 1) provides you with a range of numbers from -100 to 0 (step = 1). hence i starts at -100, increments with 1 at each iteration (-99, 98 .. etc) untill 0. Each iteration you are adding a key to the dictionary, at the end your dictionary will contain a 100 unordered keys, from -100 to 0.

In python dictionaries are always unordered. If you want an ordered dictionary, I recommend you use a collection.OrderedDict, e.g:

import collections

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

Upvotes: 1

Padraic Cunningham
Padraic Cunningham

Reputation: 180401

dicts have no order, it does not matter what order the keys are added.

If you want order use a colletions.OrderedDict which maintains insertion order:

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

Output:

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)])

You could also create your dict using a dict comprehension:

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

Upvotes: 4

Xiaotian Pei
Xiaotian Pei

Reputation: 3260

dictionary is not ordered in python

Upvotes: 4

Related Questions