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

Time:05-18

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:

{
  "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...

CodePudding user response:

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'}]})

CodePudding user response:

from collections import defaultdict

out = defaultdict(list)
for i in inp:
    out[i["id"]].append(i)
print(out) # Output: defaultdict(<class 'list'>, {'x': [{'id': 'x', 'v': 'a'}, {'id': 'x', 'v': 'b'}], 'y': [{'id': 'y', 'v': 'c'}]})

CodePudding user response:

You know, sometimes the readable answer is the best one.

for item in lst:
...:     if item["id"] not in my_dict:
...:         my_dict[item["id"]] = []
...:     my_dict[item["id"]].append(item)

CodePudding user response:

Simply run entry by entry on the list, while creating a dictionary, and set the key to the respective value.

It can be done in the long form:

new_dict = {}
for item in entries:
    new_dict.setdefault(item["id"], []).append(item)

If there is a unique id for each item in the entries, one coulduse the he shorter syntax of dictionary comprehensions:

new_dict = {item["id"]: item for item in entries}
  • Related