0

I've started a python crash course and this is an excerpt of it, pertaining to dictionaries

myDict = {'One':1.35, 2.5:'Two Point Five', 3:'+', 7.9:2}
# print the entire dictionary
print(myDict)

You’ll get {2.5: 'Two Point Five', 3: '+', 'One': 1.35, 7.9: 2}

Note that items in a dictionary are not stored in the same order as the way you declare them.

I've replicated that, and in my case the items are printed as I declared them. Why am I getting a different result? My output:

myDict = {'One':1.35, 2.5:'Two Point Five', 3:'+', 7.9:2}
#print the entire dictionary
print(myDict)

Output: {'One': 1.35, 2.5: 'Two Point Five', 3: '+', 7.9: 2}

Ajay Dabas
  • 1,404
  • 1
  • 5
  • 15
Phil
  • 43
  • 11
  • 2
    From Python 3.6 dicts maintain the insertion order, this course is probably older. – Guy Jan 13 '20 at 06:44

3 Answers3

0

Dictionaries differ from lists as they can't be indexed like them and furthermore, they are "unsorted". However, in newer versions of python, you get the same order as you used to set up the dictionary. If the course you watched used an older version of python, it should explain why the result was random.

0

dictionary always follows a key(always string format), value(any format) pair it doesn't know about order and unorders you always fetch data from the dictionary using the key name.
You can order your dictionary, but it based on the value of your dictionary, not key and your key order will be changed according to your new order values.

a zEnItH
  • 137
  • 3
  • 11
0

Python dictionaries are ordered by design since python 3.7 (sorting if it makes sense). If you use python 3.6 or lower, you can order your dictionary by storing its keys in a list, sort the list and loop through the list.

Ajay Dabas
  • 1,404
  • 1
  • 5
  • 15
m0r7y
  • 670
  • 1
  • 8
  • 27
  • I always remembered when I got different results when using dictionary in my local and in the pre-prod server (problem with order). Strugle with that for 2 days. – m0r7y Jan 13 '20 at 06:57