0

I want to print out the unsorted dictionary, but it came out sorted.

This is the code I use (Version 2.7.5 Linux):

# id and name array are not the actual input. It is just a sample input. (So no hard-coding please) 
# More importantly, I just want to figure out how to have the unsorted dictionary.

id = [1 ,4, 2] 
name = ["John" , "Mary", "Alice"]
my_dict = {}

for x in range(len(id)):
    my_dict[id[x]] = name[x]

for key, val in my_dict.items():
    print(key, val)

Expected Output:

(1, "John")
(4, "Mary")
(2, "Alice")

Actual Output:

(1, "John")
(2, "Alice")
(4, "Mary")
Selcuk
  • 57,004
  • 12
  • 102
  • 110
Jojoleo
  • 171
  • 2
  • 12
  • dictionary in python is never sorted. what you are seeing is just something that happened by chance. https://stackoverflow.com/questions/327311/how-are-pythons-built-in-dictionaries-implemented – Mox Aug 23 '19 at 06:55
  • then when i do key_list = list(my_dict.keys()). i expect to see key_list as [1 , 4 , 2 ] but it returned me with [1, 2 , 4]. – Jojoleo Aug 23 '19 at 07:07
  • pls refer to the link that i have shared. it depends on hashing – Mox Aug 23 '19 at 07:17

1 Answers1

1

It is not sorted. In Python 2.7 (and pre-3.7 releases) dictionaries are unordered; meaning them they can be stored in any order. In your test, by coincidence, they are stored in such a way. If you try the same test using Python 3.7 you will see your expected result.

If you want to keep the creation order on Python 2.7, use an OrderedDict instead.

Selcuk
  • 57,004
  • 12
  • 102
  • 110