Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 778
brocla Avatar asked Sep 15 '26 14:09

brocla


1 Answers

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.

like image 182
shriakhilc Avatar answered Sep 18 '26 06:09

shriakhilc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!