Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
david muller
Courses Plus Student 642 PointsWhy use an ordereddict instead of a regular dictionary?
I am getting the same result when using regular dictionary. I tried this code
a={}
for i in range (200):
a[str(i)]=i
for i,j in a.items():
print (i,j)
and the output is ordered.
4 Answers
Chris Freeman
Treehouse Moderator 68,468 PointsThe order read from a standard dict depends solely on the gashed values of the keys. For small integer ranges it works, but as the count increases, the hashing gets scrambled:
information.
>>> a={}
>>> for i in range (20):
... a[str(i)]=i
...
>>> for i,j in a.items():
... print (i,j)
...
18 18
14 14
19 19
9 9
8 8
7 7
6 6
5 5
4 4
3 3
2 2
1 1
10 10
17 17
12 12
11 11
13 13
16 16
0 0
15 15
Chris Freeman
Treehouse Moderator 68,468 PointsVery interesting! In the python 3.6 change doc it says:
`CPython implementation improvements:
The dict type has been reimplemented to use a more compact representation based on a proposal by Raymond Hettinger and similar to the PyPy dict implementation. This resulted in dictionaries using 20% to 25% less memory when compared to Python 3.5.`
But t heed the warning:
The order-preserving aspect of this new implementation is considered an implementation detail and should not be relied upon (this may change in the future,....
Kenneth Love
Treehouse Guest TeacherPython 3.6's dict ordering is an implementation detail, meaning it works in Python 3.6 (and likely future ones) but only for CPython and may not work in other Python variations. Because of that, you should not rely on dicts being ordered in a particular way. If you absolutely **need** your dicts to be ordered, always use OrderedDict.
david muller
Courses Plus Student 642 PointsThat's strange. I just tried the above code and the output is ordered. I even increased the range to 2000 and still the output is ordered. I am using python 3.6
david muller
Courses Plus Student 642 PointsIt seems that dict are ordered by default in python 3.6 https://stackoverflow.com/questions/39980323/dictionaries-are-ordered-in-python-3-6
Chris Freeman
Treehouse Moderator 68,468 PointsChris Freeman
Treehouse Moderator 68,468 PointsTagging Kenneth Love to be aware of dict key ordering changes in Python3.6 in case it might affect challenge functionality.