3

I have a json that is a list of dictionaries that looks like this:

I am getting it from MySQL with pymysql

[{
    "id": "123",
    "name": "test",
    "group": "test_group"
},
{
    "id": "123",
    "name": "test",
    "group": "test2_group"
},
{
    "id": "456",
    "name": "test2",
    "group": "test_group2"
},
{
    "id": "456",
    "name": "test2",
    "group": "test_group3"
}]

I need to group it so each "name" will have just one dict and it will contain a list of all groups that under this name. something like this :

[{
    "id": "123",
    "name": "test",
    "group": ["test2_group", "test_group"]
},
{
    "id": "456",
    "name": "test2",
    "group": ["test_group2", "test_group3"]
}]

I would like to get some help, Thanks !

1
  • 1
    please post your code you tried. Commented Oct 27, 2018 at 6:32

1 Answer 1

6

You can use itertools.groupby for grouping of data. Although I don't guarantee solution below to be shortest way but it should do the work.

# Your input data
data = [] 

from itertools import groupby

res = []
key_func = lambda k: k['id']

for k, g in groupby(sorted(data, key=key_func), key=key_func):
    obj = { 'id': k, 'name': '', 'group': []}
    for group in g:
        if not obj['name']:
            obj['name'] = group['name']
        obj['group'].append(group['group'])
    res.append(obj)

print(res)

It should print the data in required format.

Sign up to request clarification or add additional context in comments.

1 Comment

@Eyal.D I've removed is_new. Look for the updated answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.