Python Ordering a Dictionary After the Fact

BustACode 1 Tallied Votes 462 Views Share

Note: In Python 2.7 use: from __future__ import print_function to use examples.

In Python, by default, the key and value pairs in a dictionary are stored as hashes, therefore dictionaries do not retain the order in which values were added, and cannot be ordered.

v_Dict ={}
v_Dict["First"] = 99
v_Dict["Second"] = 45
v_Dict["Third"] = 234
print(v_Dict) ## {'Second': 45, 'Third': 234, 'First': 99}

No order at all.

To maintain an ordered dictionary one must use the collection module's "OrderedDict()."
Normally one would declare a dictionary to be ordered like so:

from collections import OrderedDict
v_Dict = OrderedDict()
v_Dict["First"] = 99
v_Dict["Second"] = 45
v_Dict["Third"] = 234
print(v_Dict) ## OrderedDict([('First', 99), ('Second', 45), ('Third', 234)])

An OrderedDict() maintains the order pairs were added.

However, from time to time I find that OrderedDict() is not up to the task. Like here with zip:

from collections import OrderedDict
d_Dict = OrderedDict()
v_Keys = [45, 50, 20]
v_Values = [3.0, 5.0, 2.0]
d_Dict = dict(zip(v_Keys, v_Values))
print(d_Dict) ## {50: 5.0, 20: 2.0, 45: 3.0}

Order is lost again.

To get order back, one must sort the dictionary on the pairs from within OrderedDict(). Like so:

from collections import OrderedDict
v_Keys = [45, 50, 20]
v_Values = [3.0, 5.0, 2.0]
d_Dict = dict(zip(v_Keys, v_Values))
d_Dict = OrderedDict(sorted(d_Dict.items()))
print(d_Dict) ## OrderedDict([(20, 2.0), (45, 3.0), (50, 5.0)])

Order is restored.

I hope someone finds this beneficial.

DragonMastur 23 Light Poster

My dad gave me a programing idea but I needed ordered dictionaries. I could solve it till now. Thanks!

megaflo 29 Newbie Poster

"Order is lost again" is incorrect. You've created an empty OrderDict() called d_Dict, then reassigned the name d_Dict to an ordinary dict() created by calling zip() on your lists of keys and values.

BustACode commented: You are correct. Thanks. +1
DragonMastur 23 Light Poster

Change the dict(zip(v_Keys, v_Values)) to OrderedDict(zip(v_Keys, v_Values)), on line 4. Thanks megaflo!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.