User Tools

Site Tools


convert_dict_of_dicts_to_list_of_dicts

convert dict of dicts to list of dicts

task

Convert

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

to

  lod = [
      {
          "name": "alice",
          "lang": "python",
          "level": "expert"
      },
      {
          "name": "bob",
          "lang": "perl",
          "level": "noob"
      }
  ]

solution

lod = [dict(value, name=key) for key, value in dod.items()]

Example:

$ ipython

In [1]:
dod = {
    "alice":
    {
        "lang": "python",
        "level": "expert"
    },
    "bob":
    {
        "lang": "perl",
        "level": "noob"
    }
}

In [2]:
dod
Out[2]:
{'alice': {'lang': 'python', 'level': 'expert'},
 'bob': {'lang': 'perl', 'level': 'noob'}}

In [3]:
lod = [dict(value, name=key) for key, value in dod.items()]

In [4]:
lod
Out[4]:
[{'lang': 'python', 'level': 'expert', 'name': 'alice'},
 {'lang': 'perl', 'level': 'noob', 'name': 'bob'}]

System information: python 3.9.4 and ipython 7.22.0

Ref

convert_dict_of_dicts_to_list_of_dicts.txt · Last modified: 2021/07/12 20:44 by admin