Aggregate sets according to keys with defaultdict python

試著忘記壹切 提交于 2019-12-02 07:45:58

You can use a tuple as a key here, for eg. ('Yankees', '1994'):

from collections import defaultdict
dic = defaultdict(list)
with open('abc') as f:
    for line in f:
        key,val  = line.split('|')
        keys = tuple(x.strip('()') for x in key.split())
        vals = [x.strip() for x in val.split(', ')]
        dic[keys].append(vals)
print dic
for k,v in dic.iteritems():
    print "{}({})|{}".format(k[0],k[1],"|".join([", ".join(x) for x in v]))

Output:

defaultdict(<type 'list'>, 
{('Yankees', '1994'): [['Abbot', 'Jim']],
 ('Yankees', '2000'): [['Buddies', 'Mike'], ['Canseco', 'Jose']],
 ('Yankees', '1993'): [['Abbot', 'Jim'], ['Assenmacher', 'Paul']]})

Yankees(1994)|Abbot, Jim
Yankees(2000)|Buddies, Mike|Canseco, Jose
Yankees(1993)|Abbot, Jim|Assenmacher, Paul
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!