我目前有一个嵌套的字典:
tmpDict = {0, {'TestRun1_lastRuntime': [3, 'avg'],
'TestRun1_maxRuntime': [5, 'max'],
'TestRun2_lastRuntime': [2, 'avg'],
'TestRun2_maxRuntime': [4, 'max'],
},
1, {'TestRun1_lastRuntime': [6, 'avg'],
'TestRun1_maxRuntime': [7, 'max'],
'TestRun2_lastRuntime': [4, 'avg'],
'TestRun2_maxRuntime': [5, 'max'],
}
}
我试着想办法把这个字典变成:
newDict = {0, {'TestRun1': [[3, 'avg'], [5, 'max']],
'TestRun2': [[2, 'avg'], [4, 'max']],
},
1, {'TestRun1': [[6, 'avg'], [7, 'max']],
'TestRun2': [[4, 'avg'], [5, 'max']],
}
}
第一个问题,这可能吗?如果是,我该怎么做?
下面的代码似乎可以运行
from typing import NamedTuple
class TestStats(NamedTuple):
avg: float
max: float
d = {0: {'TestRun1_lastRuntime': [3, 'avg'],
'TestRun1_maxRuntime': [5, 'max'],
'TestRun2_lastRuntime': [2, 'avg'],
'TestRun2_maxRuntime': [4, 'max'],
},
1: {'TestRun1_lastRuntime': [6, 'avg'],
'TestRun1_maxRuntime': [7, 'max'],
'TestRun2_lastRuntime': [4, 'avg'],
'TestRun2_maxRuntime': [5, 'max'],
}
}
dd = {}
for k, v in d.items():
seen = set()
cnt = 0
for kk, vv in v.items():
if dd.get(k) is None:
dd[k] = {}
test_name, _ = kk.split('_')
if vv[1] == 'avg':
_avg = vv[0]
cnt += 1
elif vv[1] == 'max':
_max = vv[0]
cnt += 1
if cnt == 2:
dd[k][test_name] = TestStats(_avg, _max)
cnt = 0
for k, v in dd.items():
print(f'{k} -> {v}')
输出0 -> {'TestRun1': TestStats(avg=3, max=5), 'TestRun2': TestStats(avg=2, max=4)}
1 -> {'TestRun1': TestStats(avg=6, max=7), 'TestRun2': TestStats(avg=4, max=5)}