Search code examples
pythonpython-itertools

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.

I have this:

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

And want this:

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

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

Solution

  • 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)