-1

I'm trying to create a dictionary where the indices are a mix of strings ('20' & '0') and integers (10 & 11) but every time the dictionary is printed out the output seems to change randomly. I've read that dictionaries in python are supposed to maintain the order of the elements inserted to the dictionary, so why does this shuffling of the elements occur?

arr = {};
arr['20'] = "hello"
arr['0'] = "hey"
arr[10] = "hi"
arr[11] = "yo"

print(arr)

I would expect the output to be:

{'20: 'hello', '0': 'hey', 10: 'hi', 11: 'yo'}

but the output ends up reordering each element in the array and converting 10 & 11 into strings:

{'20': 'hello', 10: 'hi', 11: 'yo', '0': 'hey'}
Akaisteph7
  • 5,034
  • 2
  • 20
  • 43
  • I get `{'20': 'hello', '0': 'hey', 10: 'hi', 11: 'yo'}` on my machine. And 10 and 11 are not strings in the output you are showing. I think you might be confused. – Akaisteph7 Jul 12 '19 at 18:05
  • 1
    Just a note, this is not an array, this is a dictionary. – Jmonsky Jul 12 '19 at 18:07
  • "{}" does not create an array, it creates a dictionary. Elements in a dictionary are not ordered for Python <= 3.6, although the CPython implementation has ordered dicts for 3.6. Since Python 3.7, dicts are insertion-ordered. See this answer for more details: https://stackoverflow.com/a/39980744/4862830 – Alexander Fasching Jul 12 '19 at 18:10

1 Answers1

1

Just for clarification, the data structure you're using is a python "dictionary" not an array. It maps keys to values. Python dictionaries do not have an internal ordering, so it will simply print in the order you've entered it in.

If you want the dictionary in order, you can use a structure called an OrderedDict:

from collections import OrderedDict
exampleDict = OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 4)])
codeman51
  • 156
  • 8
  • Python dictionaries are "insertion ordered" since Python 3.7. I can't find a good reference where this behavior is explained in detail, but it's occasionally mentioned in the docs: https://docs.python.org/3.7/library/stdtypes.html#dict.values – Alexander Fasching Jul 12 '19 at 18:19