Canonical conversion of dict of dicts to list of dicts

dn PythonList at DancesWithMice.info
Tue Mar 30 15:07:59 EDT 2021


On 31/03/2021 01.22, Loris Bennett wrote:
> 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
...

>>>
>>> than just
>>>
>>>   lod = []
>>>   for name in dod:
>>>       d = dod[name]
>>>       d["name"] = name
>>>       lod.append(d)


Please be aware of the 'law of unintended consequences' - what
functional programmers call "side-effects"!

At the end of the above code, not only has "lod" been created (per spec)
but "dod" is no longer what it once was.

Thus, future code may not rely upon the (above) structure. Of course, if
by "convert" you mean transform, ie that "dod" will be del()[eted]
afterwards, such may be completely unimportant.


from pprint import pprint as pp
import copy

dod = {
      "alice":
      {
          "lang": "python",
          "level": "expert"
      },
      "bob":
      {
          "lang": "perl",
          "level": "noob"
      }
}

original = copy.deepcopy( dod )
lod = []
for name in dod:
    d = dod[name]
    d["name"] = name
    lod.append(d)

print( original == dod )
pp(dod)
pp(original)


False
{'alice': {'lang': 'python', 'level': 'expert', 'name': 'alice'},
 'bob': {'lang': 'perl', 'level': 'noob', 'name': 'bob'}}
{'alice': {'lang': 'python', 'level': 'expert'},
 'bob': {'lang': 'perl', 'level': 'noob'}}

-- 
Regards,
=dn


More information about the Python-list mailing list