-1

Assuming that I'm using the following OrderedDict:

order_dict = OrderedDict([("a",1), ("b",2), ("c",3)])

At some point, I would like to get the (key,value) items and define an iterator, and start moving it once desired:

ordered_dict_items_iter = iter(ordered_dict.items())
...
key,val = next(ordered_dict_items_iter)
...

I'd like to know if order_dict.items() will also preserve the same order?

As I observed it seems that it does preserve the order, however I couldn't prove it.

3 Answers3

0

It does. The idea of OrderedDict is that is behaves exactly as a dictionary, but internally it's a list of tuples, representing key-values pairs, so that order is preserved. All dictionary methods are replicated using this list of tuples.

Note: After python 3.7, standard dictionaries are also guaranteed to maintain insertion order.

blue_note
  • 27,712
  • 9
  • 72
  • 90
0

Yes, it'll preserve the order you specify while initiliazing the dictionary.

0

Yes. OrderedDict.items() will return the items in the order they are inserted.

If you check the implementation of OrderedDict, you can see that items returns _OrderedDictItemsView.

class OrderedDict(dict):
    ...
    ...
    def items(self):
        "D.items() -> a set-like object providing a view on D's items"
        return _OrderedDictItemsView(self)

And if you dig deep and find the implementation of _OrderedDictItemsView,

class _OrderedDictItemsView(_collections_abc.ItemsView):

    def __reversed__(self):
        for key in reversed(self._mapping):
            yield (key, self._mapping[key])

And if you go deeper to check the _collections_abc.ItemsView, you will see that,

class ItemsView(MappingView, Set):
    ...
    ...
    def __iter__(self):
        for key in self._mapping:
           yield (key, self._mapping[key])

And further down the MappingView, you will see,

class MappingView(Sized):

    __slots__ = '_mapping',

    def __init__(self, mapping):
        self._mapping = mapping

Now our journey has reached it's destination, and we can see that the _mapping is the OrderedDict we created and it is always in order. The __iter__ method ItemsView, just iterates through each key value in the OrderedDict. Hence the proof :)

han solo
  • 6,390
  • 1
  • 15
  • 19