0

It is first time that I faced such kind of problem. Hope you guys can help me.

Basically I have:

months= {"01": "January","02": "February","03": "March","04": "April","05": "May","06": "June","07": "July","08": "August","09": "September","10": "October","11": "November","12": "December"}
x=[]
my_xticks = []
for key in months.keys():
    x.append(int(key))
for value in months.values():
    my_xticks.append(value)

Every month of the year in dictionary. But when I prited my x and y list, I saw that they changed its order.

Then I checked via (pythontutor.com) into global frame of this code, and saw this:

Global Frame of my code

How can I change it, to add(append) with right order into my list ?

Nate
  • 33
  • 5
  • Dictionaries are unsorted by nature. do `for key in sorted(months.keys())` to get it ordered. – Torxed Dec 18 '16 at 15:13

1 Answers1

2

Use collections.OrderedDict. The normal dictionary does not guaranteed order of keys. Don't pass the existing dictionary to the constructor of orderedDict, because the order has already been lost. Instead, declare your data in a structure that retains ordering, like

import collections
months_data = [("01", "Jan"), ("02", "Feb"), ...]
months = collections.OrderedDict(months_data)

Now you can iterate with the order being the same every time

blue_note
  • 27,712
  • 9
  • 72
  • 90