我想知道是否有一种简单有效的方法来格式化此正式字典为所示结果?基本上,时间键用于对字典进行分组,变量名的值用作键,值键作为值。
例如,这是字典列表:
testdata =[{
'frequency': 'monthly',
'level': '1',
'time': '2017 Jan',
'value': 99.524,
'variableCode': 'M212191.1',
'variableName': 'All Items'},
{'frequency': 'monthly',
'level': '2',
'time': '2017 Jan',
'value': 105.12,
'variableCode': 'M212191.1.0',
'variableName': 'Food'},
{'frequency': 'monthly',
'level': '1',
'time': '2017 Feb',
'value': 99.521,
'variableCode': 'M212191.1',
'variableName': 'All Items'},
{'frequency': 'monthly',
'level': '2',
'time': '2017 Feb',
'value': 105.078,
'variableCode': 'M212191.1.0',
'variableName': 'Food'},
]
但是我希望它具有以下格式的结果:
testdata = [
{
'time': '2017 Jan',
'All Items': 99.524,
'Food':105.12
},
{
'time': '2017 Feb',
'All Items': 99.521,
'Food':105.078
},
]
到目前为止,这是我坚持的进度。
import itertools
import operator
import pprint
result = sorted(testdata, key = lambda i: i['time'])
list1 = []
for key, items in itertools.groupby(result, operator.itemgetter('time')):
list1.append(list(items))
pprint.pprint(list1)
输出:
[[{'frequency': 'monthly',
'level': '1',
'time': '2017 Feb',
'value': 99.521,
'variableCode': 'M212191.1',
'variableName': 'All Items'},
{'frequency': 'monthly',
'level': '2',
'time': '2017 Feb',
'value': 105.078,
'variableCode': 'M212191.1.0',
'variableName': 'Food'}],
[{'frequency': 'monthly',
'level': '1',
'time': '2017 Jan',
'value': 99.524,
'variableCode': 'M212191.1',
'variableName': 'All Items'},
{'frequency': 'monthly',
'level': '2',
'time': '2017 Jan',
'value': 105.12,
'variableCode': 'M212191.1.0',
'variableName': 'Food'}]]
答案 0 :(得分:1)
我认为您已经足够靠近-只需再遍历这些项目即可。
from itertools import groupby
from operator import itemgetter
d = []
for k, grp in groupby(testdata,key=itemgetter("time")):
temp = {"time":k}
for i in grp:
temp[i.get("variableName")] = i.get("value")
d.append(temp)
print (d)
结果:
[{'time': '2017 Jan', 'All Items': 99.524, 'Food': 105.12}, {'time': '2017 Feb', 'All Items': 99.521, 'Food': 105.078}]
答案 1 :(得分:0)
使用itertools.groupby
:
import itertools
records = []
def get_dt(x):
return x['time']
for key, group in itertools.groupby(testdata, get_dt):
groups = list(group)
rec = {}
rec['time'] = key
rec['All Items'] = sum([x['value'] for x in groups if x['variableName']=='All Items'])
rec['Food'] = sum([x['value'] for x in groups if x['variableName']=='Food'])
records.append(rec)
print(records)
# [{'time': '2017 Jan', 'All Items': 99.524, 'Food': 105.12},
# {'time': '2017 Feb', 'All Items': 99.521, 'Food': 105.078}]
答案来自{em> this solution 来自How to create a list based on same value of a dictionary key?