Skip to main content

Sort Group and sort JSON array of dictionaries by repeatable keys in Python

edited title
Link
Eyal.D
  • 560
  • 3
  • 18

Sort JSON array of dictionaries by repeatable keys in Python

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 sortgroup 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 !

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 sort 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 !

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 !

Source Link
Eyal.D
  • 560
  • 3
  • 18
Loading