提问人:darklord84 提问时间:4/19/2023 更新时间:4/19/2023 访问量:37
在 python 中将值从一个字典转换为另一个字典作为 key:value
Converting values from one dictionary to another dictionary as key:value in python
问:
我有一种情况,我需要读取一个 json 文件,其中包含每 5 分钟进入我的系统的不同事件的统计信息。我需要根据事件汇总每个事件的计数,并将其传递到另一个字典中 这是我的示例输入字典json
"data": [
{
"recievedTime": "2023-04-10T00:05:00.000Z",
"data": [
{
"EventType": "Call",
"NumberOfEvents": 1000
},
{
"EventType": "SMS",
"NumberOfEvents": 55
}
]}
"recievedTime": "2023-04-10T00:10:00.000Z",
"data": [
{
"EventType": "Call",
"NumberOfEvents": 2003
},
{
"EventType": "SMS",
"NumberOfEvents": 45
}
]}
]
我希望输出将事件计数的总和放在另一个json对象中,如下所示:
"data" : [ {"Call": 3003,"SMS" : 100}]
我该如何解决这个问题?
答:
1赞
Ertersy
4/19/2023
#1
您可以使用循环循环访问输入字典中的事件,并将每个事件类型的计数相加。下面是实现此目的的一些示例代码:
import json
input_data = {
"data": [
{
"recievedTime": "2023-04-10T00:05:00.000Z",
"data": [
{
"EventType": "Call",
"NumberOfEvents": 1000
},
{
"EventType": "SMS",
"NumberOfEvents": 55
}
]
},
{
"recievedTime": "2023-04-10T00:10:00.000Z",
"data": [
{
"EventType": "Call",
"NumberOfEvents": 2003
},
{
"EventType": "SMS",
"NumberOfEvents": 45
}
]
}
]
}
output_data = {}
for entry in input_data['data']:
for event in entry['data']:
event_type = event['EventType']
event_count = event['NumberOfEvents']
if event_type in output_data:
output_data[event_type] += event_count
else:
output_data[event_type] = event_count
output_json = json.dumps({'data': [output_data]})
print(output_json)
这将产生所需的输出:
{"data": [{"Call": 3003, "SMS": 100}]}
1赞
Bryce Chan
4/19/2023
#2
其实很简单,只需要我们 Python 内置的 json 模块来解析 JSON 数据,然后循环遍历数据数组即可。
你可以像这样做
import json
input_data = {
"data": [
{
"recievedTime": "2023-04-10T00:05:00.000Z",
"data": [
{
"EventType": "Call",
"NumberOfEvents": 1000
},
{
"EventType": "SMS",
"NumberOfEvents": 55
}
]
},
{
"recievedTime": "2023-04-10T00:10:00.000Z",
"data": [
{
"EventType": "Call",
"NumberOfEvents": 2003
},
{
"EventType": "SMS",
"NumberOfEvents": 45
}
]
}
]
}
event_counts = {}
for item in input_data['data']:
for event in item['data']:
event_type = event['EventType']
event_count = event['NumberOfEvents']
if event_type not in event_counts:
event_counts[event_type] = event_count
else:
event_counts[event_type] += event_count
output_data = {"data": []}
for event_type, event_count in event_counts.items():
output_data["data"].append({event_type: event_count})
print(json.dumps(output_data))
输出
{
"data": [
{
"Call": 3003
},
{
"SMS": 100
}
]
}
评论