Tim
Tim

Reputation: 99418

The keys of a dictionary are not in the order when they are added?

>>> d={}
>>> d['c']=3
>>> d['b']=2
>>> d['a']=1
>>> d
{'a': 1, 'c': 3, 'b': 2}
>>> d.keys()
['a', 'c', 'b']

Are the keys in a dictionary not ordered in the same order they are added into the dictionary? What order are they in?

What shall I do if I want to have the keys of a dictionary in the order that they are added into the dictionary?

Thanks.

Upvotes: 1

Views: 57

Answers (2)

dust
dust

Reputation: 512

Python dictionaries don't preserve order, and you cannot count on any particular order. Dictionary is a store for values where, by design, values are to be referred to by their keys – and not by a particular "slot" in which they are.

If you need to preserve order of added elements, use lists where a "slot" is referred to by an index, e.g. myList[3]. If you need to have 2 values coupled together (corresponding a "key" and a "value" as in your example), use a list of tuples.

Upvotes: 2

kindall
kindall

Reputation: 184161

dict is an unordered data structure. Keys will come out in some order when you iterate over them, but this may bear little resemblance to the order in which they were added. In return, you get O(1) lookup.

Use collections.OrderedDict if you need to retain the order.

Upvotes: 5

Related Questions