Canonical conversion of dict of dicts to list of dicts

Chris Angelico rosuav at gmail.com
Tue Mar 30 11:25:18 EDT 2021


On Wed, Mar 31, 2021 at 1:56 AM Travis Griggs <travisgriggs at gmail.com> wrote:
>
>
> > On Mar 30, 2021, at 12:11, Stestagg <stestagg at gmail.com> wrote:
> >
> > For completeness, from 3.5 onwards, you can also do the following:
> >
> > [{'name': n, **d} for n, d in dod.items()]
> >
>
> Reading through these, personally I like this one best. I'm curious what about it was enabled in 3.5? Was **kwarg expansion inside a dict literal not possible before then? Anyway, I like that it uses simple elemental parts that have been around a long long time in Python.
>

Indeed:

https://www.python.org/dev/peps/pep-0448/

Some other relevant enhancements include dictionaries becoming ordered
(3.7), and gaining the ability to be merged with the | (bitwise-or)
operator (3.9). I'd generally recommend targeting 3.7 if possible,
although often things won't be horribly broken without dict ordering.
There aren't many platforms still around that have anything 3.3 or
older, and only a few that ship 3.4, so it's not too hard to demand
3.5+, but if 3.4 support matters, the only option is the dict
constructor.

Be aware, btw, that none of these options is quite the same as the
original code posted. They all construct a *new* dictionary that has
all the same contents, plus the name; the original would mutate the
*existing* dictionary, so if you look at the original lod, it would
now have names all through it. (On the other hand, this means
incurring the cost of constructing a new dict, although that shouldn't
be too expensive.)

ChrisA


More information about the Python-list mailing list