我希望您知道是否有一种简单有效的方法将这个正式的字典格式化为所示的结果?基本上,时间键用于对字典进行分组,变量名称的值用作键,值键用作值。例如,下面是字典列表:
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'}]]
itertools.groupby
。 - Paul Rooneygroupby
会很好,但它假设项目已按time
排序。这是真的吗? - Mark