2

I am learning about python collections. It is written about Ordered Dictionary that "OrderedDict preserves the order in which the keys are inserted. A regular dict doesn’t track the insertion order, and iterating it gives the values in an arbitrary order. By contrast, the order the items are inserted is remembered by OrderedDict."

So i tried to understand it by a program:

from collections import OrderedDict 

d = dict()
d['a'] = 1
d['b'] = 2
d['c'] = 3
d['d'] = 4
  
for key, value in d.items(): 
    print(key, value) 
  
print("\nThis is an Ordered Dict:\n") 
od = OrderedDict() 
od['a'] = 1
od['b'] = 2
od['c'] = 3
od['d'] = 4
  
for key, value in od.items(): 
    print(key, value) 

OUTPUT

a 1
b 2
c 3
d 4

This is an Ordered Dict:

a 1
b 2
c 3
d 4
>>> 

But the output for both is the same. So why should I use Ordered Dictionary?

Asim
  • 85
  • 1
  • 11

2 Answers2

1

Since python 3.7 Dictionary order is guaranteed to be insertion order. check this answer for similar question link

Ram Kiran
  • 66
  • 2
  • Starting from Python 3.6 dict order is garanteed in Cpython but not for the other implementations. see [here](https://stackoverflow.com/questions/39980323/are-dictionaries-ordered-in-python-3-6) – Chiheb Nexus Jul 12 '20 at 13:05
  • 1
    @ChihebNexus It was also guaranteed even before 3.6 for PyPy, which is the next most used implementation after CPython. – Arthur Tacca Jul 12 '20 at 13:10
-1

because-- If the value of a certain key is changed, the position of the key remains unchanged in OrderedDict.

  • Welcome to Stack Overflow! Thanks for contributing by posting an answer, but in this case it seems you haven't got the right explanation. But please do answer again when you see something in future you're more sure of. – Arthur Tacca Jul 12 '20 at 12:51