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