0

I'm having a hard time keeping a dictionary in its original unsorted order. Here's my code:

monthCountDict = {'Jan': 0, 'Feb': 0, 'Mar': 0, 'Apr': 0, 'May': 0,
              'Jun': 0, 'Jul': 0, 'Aug': 0, 'Sept': 0, 'Oct': 0, 'Nov': 0, 'Dec': 0}


def monthCalculator(monthNumber):
    numberToMonthList = ['', 'Jan', 'Feb', 'Mar', 'Apr', 'May',
                     'Jun', 'Jul', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec']

    monthName = numberToMonthList[monthNumber]
    monthCountDict[monthName] += 1

    return monthCountDict

The above method of my code receives monthNumber(1,2,3 and so on) and finds its relevant monthName from numberToMonthList. This monthName's value in the dictionary monthCountDict is incremented with 1. And so on many times values are incremented for different months and every time dictionary is returned.

When I try printing the final dictionary returned, it seems to be sorted in the order of insertion. And the order of months gets jumbled!!

How do I get away with this?

petezurich
  • 9,280
  • 9
  • 43
  • 57
Abbas
  • 773
  • 6
  • 16
  • 1
    If your Python version is < 3.6 then you can use `OrderedDict`. – meowgoesthedog Mar 22 '19 at 15:28
  • 1
    Dictionaries by default are an unsorted type. You should use `OrderedDict` from the collections module instead. – rgk Mar 22 '19 at 15:28
  • 1
    Use either `python3.7` or the `collections.OrderedDict` module :) – han solo Mar 22 '19 at 15:28
  • 1
    @hansolo: In CPython (and PyPy equivalent to) 3.6, [plain `dict` is also insertion ordered as an implementation detail](https://docs.python.org/3/whatsnew/3.6.html#new-dict-implementation). So as long as you're only using those interpreters, 3.6 is enough. Technically, the docs say not to count on it in 3.6 because it might change, but given it becomes official in 3.7 (and therefore *won't* change), I think you're safe. – ShadowRanger Mar 22 '19 at 15:53
  • @ShadowRanger Yes, it is safe. Just to make sure :) – han solo Mar 22 '19 at 16:45

0 Answers0