-4

I created a dictionary a and tried to use method keys() to return its keys. Below is what I got. I notice the output of keys() are not in alphabetical order or original order as in the dictionary.

a
Out[1]: {1: 'JAN', 2: 'FEB', 3: 'MAR', 'APR': 4, 'MAY': 5}

a.keys()
Out[2]: ['APR', 1, 2, 3, 'MAY']

Anyone could help me understand why this happens. and what's the order keys() is using here?

  • No order at all.... That's because python dictionaries are not key-ordered... You were just lucky first time. :p – sarveshseri Feb 04 '15 at 13:34
  • because its not , you need to sort it `>>> a={1: 'JAN', 2: 'FEB', 3: 'MAR', 'APR': 4, 'MAY': 5} >>> sorted(a.keys()) [1, 2, 3, 'APR', 'MAY'] ` – Mazdak Feb 04 '15 at 13:36
  • @littlejoshua dictionaries **are not** ordered: https://docs.python.org/2/tutorial/datastructures.html `the keys used in the dictionary, in arbitrary order (if you want it sorted, just apply the sorted() function to it)` – Aleksander Lidtke Feb 04 '15 at 13:36
  • use ordereddict instead. – Barun Sharma Feb 04 '15 at 13:39

1 Answers1

1

Dictionary in python using hashes for keys, and it doesn't saves order. So, you cant count on keys order - it may differ during runs and calls. If you need hashmap and save order, you should use ordered dict

Slam
  • 8,112
  • 1
  • 36
  • 44