首页 > 解决方案 > 更新值并保留python字典上的键

问题描述

我有一个停车位应用程序,我想在其中计算一周中的可用天数以及每天的总可用小时数。

我有不同的城市,有不同的时移,有些是全职的(例如 7:00-20:00),有些是分开的时间(例如 7:00-14:00 和 16:00-20:00)。

这是我尝试的循环:

def get_available_hours(self):
    _dict = []
    time = 0
    query_set = TimeTableCity.objects.filter(city_id=self._city_id)
    for i in query_set:
        initial_hour_datetime = datetime.strptime(i.initial_hour, '%H:%M')
        end_hour_datetime = datetime.strptime(i.end_hour, '%H:%M')
        time = end_hour_datetime - initial_hour_datetime
        _dict.append({i.day_table.id: time.seconds / 3600})
        time = 0
    return _dict

最后返回的dict如下:

[{4: 5.0}, {4: 4.0}, {5: 5.0}, {5: 4.0}, {1: 5.0}, {1: 4.0}, {2: 5.0}, {2: 4.0}, {3: 5.0}, {3: 4.0}]

键是星期几,值是该班次的小时数。有没有办法对同一个键的值求和?

标签: pythondjangodictionary

解决方案


看看计数器。https://docs.python.org/3/library/collections.html#collections.Counter 它可用于对具有相同键的单独字典的值求和。IE

from collections import Counter

a = {'a': 5, 'b': 7}
b = {'a': 3, 'b': 2, 'c': 5}
dict(Counter(a)+Counter(b))

--

Out[7]: {'a': 8, 'b': 9, 'c': 5}

推荐阅读