1

I want to get my keys in my order. But, it doesn't work with dictionary and Collections.OrderedDict.

from collections import OrderedDict

data = OrderedDict({
  "Name1": "value1",
  "Name2": "value2"
})

for key in data.keys():
  print(key)

This code shows that Name3 Name4 .... It doesn't have any order. My data doesn't have alphabetical order in keys, and I must get the keys in my order.

I found that dictionary is not designed with order. Then, what structures can I use with key and value pair? Or there is any way to use dictionary in custom order? (input order..?)

Ignacio Vergara Kausel
  • 5,521
  • 4
  • 31
  • 41
Harine
  • 99
  • 2
  • 9
  • 1
    what you want is an [OrderedDict](https://docs.python.org/3.8/library/collections.html#collections.OrderedDict) – Nullman Jan 16 '20 at 09:27
  • He's using an `OrderedDict` @Nullman (at least what he wrote). – Ignacio Vergara Kausel Jan 16 '20 at 09:28
  • Your code snippet works as expected for me (using CPython 3.7) – Ignacio Vergara Kausel Jan 16 '20 at 09:29
  • you might want to try a different way of initialising the `OrderedDict`: For example, use: `OrderedDict(name1="value1", name2="value2")`. See also [link](https://stackoverflow.com/questions/25480089/right-way-to-initialize-an-ordereddict-using-its-constructor-such-that-it-retain]). – sim Jan 16 '20 at 09:29
  • This problem makes me crazy.. It works sometimes and it doesn't work sometimes. There is no process except that. I don't know why ordered dict working in crazy.. – Harine Jan 16 '20 at 09:31

2 Answers2

3

You need to change the structure of your ordered dictionary from this

data = OrderedDict({
  "Name1": "value1",
  "Name2": "value2",
  ...
})

to this

data = OrderedDict([('Name1', 'value1'), ('Name2', 'Value2')])

High-Octane
  • 1,104
  • 5
  • 19
  • to add to your answer, the reason you need to do this is because you are first creating a regular dict, which is unordered, and then turning it into an ordrered dict which will retain THE WRONG ORDER from the regular dict you made – Nullman Jan 16 '20 at 09:32
0

tl;dr: Use Python 3.7 or above.


dicts in Python 3.7 and above are always ordered. This applies to all sorts of iterations:

Dictionaries preserve insertion order. Note that updating a key does not affect the order. Keys added after deletion are inserted at the end.

Changed in version 3.7: Dictionary order is guaranteed to be insertion order.

This also applies to the popitem() method:

Changed in version 3.7: LIFO order is now guaranteed. In prior versions, popitem() would return an arbitrary key/value pair.

https://docs.python.org/3/library/stdtypes.html#dict.popitem

Community
  • 1
  • 1
Peter Thomassen
  • 1,671
  • 1
  • 16
  • 28