Home > Blockchain >  Why do the Items in a Python ChainMap reverse order when converted to a Dictionary?
Why do the Items in a Python ChainMap reverse order when converted to a Dictionary?

Time:01-14

Why does converting a ChainMap to a dictionary reverse the order of the items?

Here is an example.

>>> d = [{'a': 1}, {'b': 2}, {'c': 3}]

>>> ChainMap(*d)
ChainMap({'a': 1}, {'b': 2}, {'c': 3})

>>> dict(ChainMap(*d))
{'c': 3, 'b': 2, 'a': 1}

I can write alternate code to combine the dictionaries that does not reverse.

But, I would like to understand why this reversal happens for ChainMap.

It seems it would be desirable to keep the order.

CodePudding user response:

ChainMap documentation mentions

Note, the iteration order of a ChainMap() is determined by scanning the mappings last to first.

The only mention of why ChainMap does this seems to be the following

This gives the same ordering as a series of dict.update() calls starting with the last mapping

Meanwhile, dict maintains insertion order since a few versions ago

Dictionaries preserve insertion order. Note that updating a key does not affect the order. Keys added after deletion are inserted at the end.

Changed in version 3.7: Dictionary order is guaranteed to be insertion order. This behavior was an implementation detail of CPython from 3.6.

So when you call dict(ChainMap(*d)), it iterates over the ChainMap i.e. reverse of the order of *d and that becomes insertion order for the new dict.

  •  Tags:  
  • Related