Canonical conversion of dict of dicts to list of dicts
Chris Angelico
rosuav at gmail.com
Tue Mar 30 07:50:02 EDT 2021
On Tue, Mar 30, 2021 at 10:41 PM Loris Bennett
<loris.bennett at fu-berlin.de> wrote:
>
> Hi,
>
> If I have dict of dicts, say
>
> dod = {
> "alice":
> {
> "lang": "python",
> "level": "expert"
> },
> "bob":
> {
> "lang": "perl",
> "level": "noob"
> }
> }
>
> is there a canonical, or more pythonic, way of converting the outer key
> to a value to get a list of dicts, e.g
>
> lod = [
> {
> "name": "alice",
> "lang": "python",
> "level": "expert"
> },
> {
> "name": "bob",
> "lang": "perl",
> "level": "noob"
> }
> ]
>
> than just
>
> lod = []
> for name in dod:
> d = dod[name]
> d["name"] = name
> lod.append(d)
>
> ?
>
I dunno about "canonical", but here's how I'd do it:
lod = [info | {"name": name} for name, info in dod.items()]
You could use {"name":name}|info instead if you prefer to have the
name show up first in the dictionary.
ChrisA
More information about the Python-list
mailing list