Reputation: 119
I have got a response after altering a list. My response looks something like this :
{
"response": [
{
"timestamp": "21:15-21:30",
"logs": [
{
"exception": "IllegalAgrumentsException",
"count": 1
}
]
},
{
"timestamp": "21:15-21:30",
"logs": [
{
"exception": "NullPointerException",
"count": 2
}
]
},..
I want the result to be something like this:-
"response": [
{
"timestamp": "21:15-21:30",
"logs": [
{
"exception": "IllegalAgrumentsException",
"count": 1
},
{
"exception": "NullPointerException",
"count": 2
} ]
}
How can I merge logs together like above in python?
Upvotes: 0
Views: 104
Reputation: 1382
response = [
{
"timestamp": "21:15-21:30",
"logs": [{"exception": "IllegalAgrumentsException", "count": 1}],
},
{
"timestamp": "21:15-21:30",
"logs": [{"exception": "NullPointerException", "count": 2}],
},
]
final = []
for k,v in groupby(response, lambda x:x.pop('timestamp')):
final.append({
'timestamp':k,
'logs':reduce(
lambda x,y: {'logs':y['logs']+x['logs']},
[*v]
)['logs']
})
print(final)
Output
[
{
"timestamp": "21:15-21:30",
"logs": [
{"exception": "IllegalAgrumentsException", "count": 1},
{"exception": "NullPointerException", "count": 2},
],
}
]
Upvotes: 0
Reputation: 169051
As with the other part of this question, it would be defaultdict
time... but we'll need OrderedDict
here to keep the original timestamp order.
import collections
input_data = [
{
"timestamp": "21:15-21:30",
"logs": [{"exception": "IllegalAgrumentsException", "count": 1}],
},
{
"timestamp": "21:15-21:30",
"logs": [{"exception": "NullPointerException", "count": 2}],
},
]
logs_by_timestamp = collections.OrderedDict()
for datum in input_data:
logs_by_timestamp.setdefault(datum["timestamp"], []).extend(datum["logs"])
output_data = [
{"timestamp": timestamp, "logs": logs}
for (timestamp, logs) in logs_by_timestamp.items()
]
print(output_data)
outputs (formatted)
[
{
"timestamp": "21:15-21:30",
"logs": [
{"exception": "IllegalAgrumentsException", "count": 1},
{"exception": "NullPointerException", "count": 2},
],
}
]
Upvotes: 2
Reputation: 162
considering your situatuation..
check out the below patch
_dict = {
"response": [
{
"timestamp": "21:15-21:30",
"logs": [
{
"exception": "IllegalAgrumentsException",
"count": 1
}
]
},
{
"timestamp": "21:15-21:30",
"logs": [
{
"exception": "NullPointerException",
"count": 2
}
]
}]}
_final = {}
for _dict in _dict.get('response'):
if not _dict.get('timestamp') in _final:
_final[_dict.get('timestamp')] = {
'timestamp': _dict.get('timestamp'),
'logs': []
}
_final[_dict.get('timestamp')]['logs'] += _dict.get('logs')
_result ={'response': list(_final.values())}
print(_result)
which will print ...
{
'response': [
{
'timestamp': '21:15-21:30',
'logs': [
{
'exception': 'IllegalAgrumentsException',
'count': 1
},
{
'exception': 'NullPointerException',
'count': 2
}
]
}
]
}
Upvotes: 1