gpt4 book ai didi

python - 合并具有相同值的字典列表的最简单方法是什么?

转载 作者:行者123 更新时间:2023-11-28 17:58:52 27 4
gpt4 key购买 nike

我想知道是否有一种简单有效的方法可以将这个正式字典格式化为如图所示的结果?基本上,时间键用于对字典进行分组,变量名的值用作键,值键用作值。

例如这里是字典列表:

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'}]]

最佳答案

我认为您已经足够接近了 - 只需再次循环遍历这些项目即可。

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}]

关于python - 合并具有相同值的字典列表的最简单方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56800465/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com