根据公共密钥值汇总一个字典列表 [英] Summarize a list of dictionaries based on common key values

查看:106
本文介绍了根据公共密钥值汇总一个字典列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的字典列表:

I have a list of dictionaries like so:

dictlist = [{'day': 0, 'start': '8:00am', 'end': '5:00pm'},
            {'day': 1, 'start': '10:00am', 'end': '7:00pm'},
            {'day': 2, 'start': '8:00am', 'end': '5:00pm'},
            {'day': 3, 'start': '10:00am', 'end': '7:00pm'},
            {'day': 4, 'start': '8:00am', 'end': '5:00pm'},
            {'day': 5, 'start': '11:00am', 'end': '1:00pm'}]

我想总结一下共享相同'start''end' times的日子。

I want to summarize days that share the same 'start' and 'end' times.

例如,

summarylist = [([0,2, 4], '8:00am', '5:00pm'),
               ([1, 3], '10:00am', '7:00pm')
               ([5], '11:00am', '1:00pm')]

我已经尝试适应我其他StackOverflow解决方案re:设置和交叉点实现这个没有运气。我试图重新使用对这个问题的解决方案无效。希望有人能指出我正确的方向。

I have tried to adapt some other StackOverflow solutions re: sets and intersections to achieve this with no luck. I was trying to re-purpose the solution to this question to no avail. Hoping someone can point me in the right direction.

推荐答案

如果您不需要您提供的确切格式,您可以使用 defaultdict

If you don't need the exact format that you provide you could use defaultdict

dictlist = [{'day': 0, 'start': '8:00am', 'end': '5:00pm'},
            {'day': 1, 'start': '10:00am', 'end': '7:00pm'},
            {'day': 2, 'start': '8:00am', 'end': '5:00pm'},
            {'day': 3, 'start': '10:00am', 'end': '7:00pm'},
            {'day': 4, 'start': '8:00am', 'end': '5:00pm'},
            {'day': 5, 'start': '11:00am', 'end': '1:00pm'}]

from collections import defaultdict

dd = defaultdict(list)

for d in dictlist:
    dd[(d['start'],d['end'])].append(d['day'])

结果:

>>> dd
defaultdict(<type 'list'>, {('11:00am', '1:00pm'): [5], ('10:00am', '7:00pm'): [1, 3], ('8:00am', '5:00pm'): [0, 2, 4]})

如果格式对您来说很重要:

And if format is important to you could do:

>>> my_list = [(v, k[0], k[1]) for k,v in dd.iteritems()]
>>> my_list
[([5], '11:00am', '1:00pm'), ([1, 3], '10:00am', '7:00pm'), ([0, 2, 4], '8:00am', '5:00pm')]
>>> # If you need the output sorted:  
>>> sorted_my_list = sorted(my_list, key = lambda k : len(k[0]), reverse=True)
>>> sorted_my_list
[([0, 2, 4], '8:00am', '5:00pm'), ([1, 3], '10:00am', '7:00pm'), ([5], '11:00am', '1:00pm')]

这篇关于根据公共密钥值汇总一个字典列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆