简体   繁体   中英

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.

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 ie reverse of the order of *d and that becomes insertion order for the new dict .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM