Hou*_*und 2 python python-itertools python-3.x python-3.8
我有下面的示例词典,
errors = [{'PartitionKey': '34', 'RowKey': '14', 'Component': 'mamba', 'Environment': 'QA', 'Error': '404 not found', 'Group': 'Test', 'Job': 'cutting', 'JobType': 'automated'}, {'PartitionKey': '35', 'RowKey': '15', 'Component': 'mamba', 'Environment': 'QA', 'Error': '404 not found', 'Group': 'Test', 'Job': 'cutting', 'JobType': 'automated'}, {'PartitionKey': '36', 'RowKey': '16', 'Component': 'mamba', 'Environment': 'Dev', 'Error': '404 not found', 'Group': 'random', 'Job': 'moping', 'JobType': 'manual'}, {'PartitionKey': '37', 'RowKey': '17', 'Component': 'mamba', 'Environment': 'QA', 'Error': '404 not found', 'Group': 'Test', 'Job': 'cutting', 'JobType': 'automated'}, {'PartitionKey': '38', 'RowKey': '18', 'Component': 'mamba', 'Environment': 'Dev', 'Error': '404 not found', 'Group': 'random', 'Job': 'moping', 'JobType': 'manual'},{'PartitionKey': '39', 'RowKey': '19', 'Component': 'Scorpio', 'Environment': 'Dev', 'Error': '500 internal error', 'Group': 'minerva', 'Job': 'cleaning', 'JobType': 'manual'},{'PartitionKey': '39', 'RowKey': '19', 'Component': 'Scorpio', 'Environment': 'Dev', 'Error': '500 internal error', 'Group': 'minerva', 'Job': 'cleaning', 'JobType': 'manual'}]
Run Code Online (Sandbox Code Playgroud)
我试图使用 python 程序查找每个环境中观察到的错误类型以及计数。就像是,
{
'QA': {
'404 not found': 10,
'500 internal error': 20,
'503 xyz': 30
},
'DEV': {
'404 not found': 10,
'500 internal error': 20,
'503 xyz': 30
}
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试使用 Python itertools groupby 来实现这一点。这是我正在尝试的片段,但我无法完全实现我想要的。任何帮助将不胜感激
from itertools import groupby
grouped = collections.defaultdict(list)
newgrouped = collections.defaultdict(list)
for item in errors:
grouped[item['Environment']].append(item)
for key, vals in grouped.items():
for val in valss:
newgrouped[group['Error']].append(group)
Run Code Online (Sandbox Code Playgroud)
您可以使用dict.setdefault子字典来初始化不存在的键,其中可以跟踪错误计数:
from operator import itemgetter
summary = {}
for env, error in map(itemgetter('Environment', 'Error'), errors):
summary.setdefault(env, {})[error] = summary.get(env, {}).get(error, 0) + 1
Run Code Online (Sandbox Code Playgroud)
给定您的示例输入,summary将变为:
{'QA': {'404 not found': 3}, 'Dev': {'404 not found': 2, '500 internal error': 2}}
Run Code Online (Sandbox Code Playgroud)
演示: https: //replit.com/@blhsing/BogusVirtualKnowledge