What is the result type of OrderedDict in Python?

196 Views Asked by At

Regarding OrderedDict, what does it exactly returns for its type? For example following code

od = OrderedDict()
od['a'] = 1
od['b'] = 2
od['c'] = 3
od['d'] = 4
print(od)

Result is:

OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 4)])

The result set seems to be pair of tuples in the list, is that right? But in fact I am able to access it the way I access dictionaries, like:

print(od['a'])
1

What am I getting wrong and how is the result interpreted?

2

There are 2 best solutions below

0
ShadowRanger On

The repr of OrderedDict is showing how you could construct an equivalent OrderedDict. The repr of any type, ideally, serves this purpose; assuming no <> are involved (to indicate it's not a programmatically useful repr), you should be able to copy and paste that back into an interactive interpreter and produce an equivalent object. This sometimes breaks down when the objects inside it don't have useful reprs themselves, but for simple built-in literals like this it's correct.

Pre-3.7, there was no language guarantee that plain dicts were ordered, so it couldn't use a dict as the "argument", and instead chose to use a list of tuples as a semi-arbitrary available ordered sequence. But that's just showing what you'd pass to the constructor to recreate it, it's still a dict, so no features or lists or tuples are involved.

They could change the repr at this point to use a dict literal, but I suspect they do not to ensure code (e.g. doctests) that rely on the old repr format doesn't break (it hardly matters what it looks like after all, so long as it's accurately depicting some way to recreate it).

0
mkrieger1 On

The type of an OrderedDict is OrderedDict:

>>> type(od)
<class 'collections.OrderedDict'>

It's a subtype of dict, that's why you can use it like a normal dictionary:

>>> issubclass(OrderedDict, dict)
True
>>> isinstance(od, dict)
True