Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to group a list of objects into a dictionary of lists based on id

I have a list of items with id. I want to group the items into separate lists according to a shared id.

For example, this is my original list:

[
  {
    "id": "x",
    "v": "a"
  },
  {
    "id": "x",
    "v": "b"
  },
  {
    "id": "y",
    "v": "c"
  }
]

I would like to output:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{
  "x": [
    {
      "id": "x",
      "v": "a"
    },
    {
      "id": "x",
      "v": "b"
    }
  ],
  "y": [
    {
      "id": "y",
      "v": "c"
    }
  ]
}

This is how I would do this with javascript:

const output = input.reduce((obj, item) => {
    if (!obj[item.id]) obj[item.id] = [];
    obj[item.id].push(item);
    return obj;
}, {})

I can’t find how to do this in python in a short and elegant way like javascript…

>Solution :

Use dict.setdefault:

>>> result = {}
>>> for dct in your_list:
...     result.setdefault(dct['id'], []).append(dct)
...
>>> result
{'x': [{'id': 'x', 'v': 'a'}, {'id': 'x', 'v': 'b'}], 'y': [{'id': 'y', 'v': 'c'}]}

Or collections.defaultdict:

>>> from collections import defaultdict
>>> result = defaultdict(list)
>>> for dct in your_list:
...     result[dct['id']].append(dct)
...
>>> result
defaultdict(<class 'list'>, {'x': [{'id': 'x', 'v': 'a'}, {'id': 'x', 'v': 'b'}], 'y': [{'id': 'y', 'v': 'c'}]})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading