按键分组字典并查找最大值

时间:2016-03-10 12:33:10

标签: python dictionary itertools

我有一个字典,其中datetime为键,ID列为值。它实际上是一天中每个时间的活跃用户数。

字典看起来像:

2016-03-09 12:13:24 [34941L, 34943L, 35183L, 35028L, 35031L, 35081L, 35091L, 35167L, 35180L]
2016-03-09 12:16:49 [34941L, 34943L, 35183L, 35028L, 35031L, 35081L, 35091L, 35167L, 35187L]
2016-03-09 12:17:14 [34941L, 34943L, 35183L, 35028L, 35031L, 35081L, 35091L, 35167L, 35187L]
2016-03-09 12:21:39 [34941L, 34943L, 35183L, 35028L, 35031L, 35081L, 35091L, 35167L]
2016-03-09 12:22:01 [34941L, 34943L, 35183L, 35028L, 35031L, 35081L, 35091L, 35188L]
2016-03-09 12:23:08 [34941L, 34943L, 35183L, 35028L, 35031L, 35081L, 35091L, 35188L]
2016-03-09 12:23:37 [35191L, 34941L, 34943L, 35183L, 35028L, 35031L, 35081L, 35091L]
2016-03-09 12:24:05 [35191L, 34941L, 34943L, 35183L, 35028L, 35031L, 35081L, 35091L]

我想要做的是制作一个包含每天最大用户数的字典。类似的东西:

2016-03-07: 25
2016-03-08: 38
2016-03-09: 12
2016-03-10: 29
编辑:我想找到每天的高峰。

所以我需要找到值列表的长度,然后按键的日期分组,最后找到组的最大值。

查找列表的长度很简单,例如:

for time, user_id in sorted(users_by_time.iteritems()):
    user_by_time[time] = len(user_id)

但我正在努力进行分组。

如何以最有效/ pythonic的方式完成分组和最大计算?

2 个答案:

答案 0 :(得分:4)

要获得每天的高峰非常容易:

from collections import defaultdict

max_count_by_day = defaultdict(int)
for dt, user_ids in users_by_time.iteritems():
    d = dt.date()
    max_count_by_day[d] = max(max_count_by_day[d], len(user_ids))

对于每天不同用户的数量,请使用defaultdict(set)

users_in_day = defaultdict(set)
for dt, user_ids in users_by_time.iteritems():
    users_in_day[dt.date()].update(user_ids)

然后将字典展平为另一个date: count

usercount_per_day = {d: len(user_ids) for d, user_ids in users_in_day.iteritems()}

答案 1 :(得分:-1)

对于分组,您可以

from collections import defaultdict
output = defaultdict(int)
for key, value in my_dict:
    b[key.date()] += len(value)

然后转换为列表并排序

output = sorted(zip(output.keys(), output.values()))