Lets say we have a json object in Python:
JavaScript
x
24
24
1
myJson = [
2
{
3
"id": "123",
4
"name": "alex",
5
"meta": {
6
"city": "boston"
7
}
8
},
9
{
10
"id": "234",
11
"name": "mike",
12
"meta": {
13
"city": "seattle"
14
}
15
},
16
{
17
"id": "345",
18
"name": "jess",
19
"meta": {
20
"city": "boston"
21
}
22
}
23
]
24
What is the most efficient way to group this data by city, so that we end up with a json in which we group the data by city such that we end up with a json as:
JavaScript
1
11
11
1
myNewJson = [
2
{
3
"city": "boston",
4
"people": [ ]
5
},
6
{
7
"city": "seattle",
8
"people": [ ]
9
}
10
]
11
… in which the content of the people are included in “people” key.
Thanks!
Advertisement
Answer
Try:
JavaScript
1
13
13
1
myJson = [
2
{"id": "123", "name": "alex", "meta": {"city": "boston"}},
3
{"id": "234", "name": "mike", "meta": {"city": "seattle"}},
4
{"id": "345", "name": "jess", "meta": {"city": "boston"}},
5
]
6
7
out = {}
8
for d in myJson:
9
out.setdefault(d["meta"]["city"], []).append(d["name"])
10
11
out = [{"city": k, "people": v} for k, v in out.items()]
12
print(out)
13
Prints:
JavaScript
1
5
1
[
2
{"city": "boston", "people": ["alex", "jess"]},
3
{"city": "seattle", "people": ["mike"]},
4
]
5