Im working with JSON in python, It new to me, and im trying to merge similar observations by key attributes. The JSON looks like this:
JavaScript
x
8
1
tempads=[
2
['doron-2020-026', ['19.0.1']],
3
['doron-2020-026', ['18.0.6']],
4
['doron-2020-023', ['19.0.0']],
5
['doron-2020-023', ['18.0.5']],
6
['doron-2020-023', ['17.0.7']]
7
]
8
I tried to create a list with unique observations using this:
JavaScript
1
4
1
for tempad in tempads:
2
ads.append(tempad[0])
3
ads = list(dict.fromkeys(ads))
4
the output is:
JavaScript
1
2
1
['doron-2020-026', 'doron-2020-023']
2
then I tried to look for that list values and to add to them the observations but for some reason, it’s only giving me back the latest one:
JavaScript
1
12
12
1
for ad in ads:
2
for i in range(0,len(tempads)-1):
3
if ad==tempads[i][0]:
4
ad=[ad,tempads[i][1]]
5
newads.append(ad)
6
print(newads)
7
8
[
9
['doron-2020-026', ['19.0.1']],
10
['doron-2020-023', ['19.0.0']]
11
]
12
Advertisement
Answer
Looks like you need a groupby.
Using itertools.groupby
. Note this works only if the list is ordered.
Ex:
JavaScript
1
13
13
1
from itertools import groupby
2
3
tempads=[
4
['doron-2020-026', ['19.0.1']],
5
['doron-2020-026', ['18.0.6']],
6
['doron-2020-023', ['19.0.0']],
7
['doron-2020-023', ['18.0.5']],
8
['doron-2020-023', ['17.0.7']]
9
]
10
11
result = [[k, [n for _, i in v for n in i]] for k, v in groupby(tempads, lambda x: x[0])]
12
print(result)
13
Output:
JavaScript
1
3
1
[['doron-2020-026', ['19.0.1', '18.0.6']],
2
['doron-2020-023', ['19.0.0', '18.0.5', '17.0.7']]]
3
If the list is unordered use a simple dict
Ex:
JavaScript
1
4
1
result = {}
2
for k, v in tempads:
3
result.setdefault(k, []).extend(v)
4
Output:
JavaScript
1
3
1
{'doron-2020-023': ['19.0.0', '18.0.5', '17.0.7'],
2
'doron-2020-026': ['19.0.1', '18.0.6']}
3