python在词典列表中找到重复项并合并

时间:2013-07-09 10:09:31

标签: python list python-2.7 dictionary duplicates

我正在使用python 2.7 我的问题与python list of dictionaries find duplicates based on value相同 除了我的唯一标识符是基于多个键(id,name,address等)

而且,基于这些键我必须合并其他一些值

有什么建议吗?

谢谢

1 个答案:

答案 0 :(得分:1)

所以在一点点帮助下我得到了这段代码

uq_map = {}
for rec in outputs:
    #Set values that are marked as unique identifiers
    key = rec["o_date"], rec["o_hour"], rec["co_name"], rec["o_student"], rec["o_class"], rec["o_day"]
    #If they exist we append them to a new defined key 
    if key in uq_map:
        item = uq_map[key]
        print "item ",item
        item['o_teacher_set'].append(rec["o_teacher"])
        item['o_location_set'].append(rec["o_location"])            
    #if not we insert them into new key            
    else:
        item = rec.copy()
        item['o_teacher_set'] = [rec["o_teacher"]]
        item['o_location_set'] = [rec["o_location"]]
        uq_map[key] = item


print uq_map
#This is the loop to remove duplicates from nwe keys
for rec in uq_map.values():
    print 'Teachers: ', '+'.join(set(rec['o_teacher_set']))

如果有更多的pythonic solutons请告诉我

谢谢你 最好的问候