Search code examples
pythondictionaryordereddict

How can I get data with order in python dictionary?


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..?)


Solution

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