Canonical conversion of dict of dicts to list of dicts
Loris Bennett
loris.bennett at fu-berlin.de
Tue Mar 30 08:22:23 EDT 2021
Jon Ribbens <jon+usenet at unequivocal.eu> writes:
> On 2021-03-30, Loris Bennett <loris.bennett at fu-berlin.de> wrote:
>> 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)
>>
>> ?
>
> There can't be a "canonical" way to perform the arbitrary data
> conversion you want, because it's arbitrary. Personally I would
> do this:
>
> [dict(data, name=name) for name, data in dod.items()]
>
> but it's of course arguable whether this is "more Pythonic" or
> indeed "better".
As I am stuck with Python 3.6 I'll go with this.
I'm not quite sure what you mean by "arbitrary". I meant "canonical" in
the sense of "standard" or "established", which it seems to me could
apply to a fairly generic conversion such as DoD -> LoD as described
above.
Thanks to you and the other for the help.
Cheers,
Loris
--
This signature is currently under construction.
More information about the Python-list
mailing list