I'm not certain this is the clearest possible code pattern to use, but
depending on the structure of your larger code, it's possible to do this,
and the compactness may help with understandability (that's a judgement
call!):

[dict(d, name=n) for n, d in dod.items()]

On Tue, Mar 30, 2021 at 12:42 PM Loris Bennett <loris.benn...@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)
>
> ?
>
> Cheers,
>
> Loris
>
> --
> This signature is currently under construction.
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to