cerebrou
cerebrou

Reputation: 5550

Not sorting keys when creating an dictionary fromkeys

When creating a dictionary from keys:

mydict = dict.fromkeys(['c1', 'c2', 'c3', 'c4', 'c5', 'c6', 'c7', 'c8', 'c9', 'c10', 'c11'], np.linspace(-1.2, -0.8, num=5))

I get the keys sorted beforehand:

'c1': array([-1.2, -1.1, -1. , -0.9, -0.8]),
'c10': array([-1.2, -1.1, -1. , -0.9, -0.8]),
'c11': array([-1.2, -1.1, -1. , -0.9, -0.8]),
'c2': array([-1.2, -1.1, -1. , -0.9, -0.8]),
...

How to get the dictionary with entries in the order as given in the list?

Upvotes: 0

Views: 78

Answers (1)

Saritus
Saritus

Reputation: 978

The problem is that the typical python dict does not allow you to define the order of its keys. If you want to do that, you need to use a OrderedDict. The necessary would be quiet small.

from collections import OrderedDict
mydict = OrderedDict.fromkeys(['c1', 'c2', 'c3', 'c4', 'c5', 'c6', 'c7', 'c8', 'c9', 'c10', 'c11'], np.linspace(-1.2, -0.8, num=5))

I can also strongly hint at looking at https://stackoverflow.com/a/39537308/10833207 with a way better explanation how dict key ordering works in python, especially for its different versions.

Upvotes: 3

Related Questions