如何基于字典键的相同值创建列表 [英] How to create a list based on same value of a dictionary key
问题描述
我正在尝试将包含相同日期的字典连接在一起,并创建这些常用日期必须具有的温度值列表,然后提取这些值的最大值和最小值.
I am trying to join together dictionaries that contain the same date, and also create a list of the temperature values that these common dates have to then pull the max and min of these values.
我有这个:
data =
[{'temp_min': 51.75, 'date': '2019-05-31', 'temp_max': 52.25},
{'temp_min': 52.5, 'date': '2019-05-31', 'temp_max': 52.87},
{'temp_min': 53.29, 'date': '2019-05-31', 'temp_max': 53.55},
{'temp_min': 68.19, 'date': '2019-06-01', 'temp_max': 75.19},
{'temp_min': 61.45, 'date': '2019-06-01', 'temp_max': 68.45},
{'temp_min': 56.77, 'date': '2019-06-01', 'temp_max': 59.77}]
并想要这个:
[{'date':'2019:05-31', 'temp_min':[51.75, 52.5, 53.29], 'temp_max':
[52.25, 52.87, 53.55]}, {'date':'2019:06-01','temp_min':[68.19,
61.45, 56.77], 'temp_max':[75.19, 68.45, 59.77]}]
我正在尝试使用itertools groupby来执行此操作,但是在尝试创建上述输出时陷入困境.如果对此有其他解决方法,也欢迎您.我不确定如何将分组重新放入字典中,以及如何保留唯一的日期.
I am trying to do this using itertools groupby but am getting stuck when I try to create the output as mentioned above. If there is a different approach to this that is also welcome. I wasn't sure how to get the groupings back into a dictionary and also keep the unique date.
def get_temp(temp):
return temp['date']
grouping = itertools.groupby(data, get_temp)
for key, group in grouping:
print(key)
for d in group:
print(d['temp_max'])
推荐答案
在组中迭代以区分最小值和最大值以分隔字典的键:
Iterate over group to sort out mins and maxs to separate keys of the dictionary:
def get_temp(temp):
return temp['date']
lst = []
for key, group in itertools.groupby(data, get_temp):
groups = list(group)
d = {}
d['date'] = key
d['temp_min'] = [x['temp_min'] for x in groups]
d['temp_max'] = [x['temp_max'] for x in groups]
lst.append(d)
print(lst)
这篇关于如何基于字典键的相同值创建列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!