美文网首页
Python字典相同值的键合并

Python字典相同值的键合并

作者: 还是那个没头脑 | 来源:发表于2019-08-23 17:52 被阅读0次

    方法一:

    from collections import defaultdict
    
    a_dict = {'aa': {1, 2, 3, 5}, 'bb': {2, 3, 4, 5}, 'cc': {3, 4, 5}}
    a_set = set()
    result = defaultdict(set)
    for k, v in a_dict.items():
        a_set = a_set | v
    for i in a_set:
        dict_key = list()
        for key in a_dict:
            if i in a_dict[key]:
                dict_key.append(key)
        result['_'.join(sorted(dict_key))].add(i)
    print(result)
    

    方法二:

    from functools import reduce
    
    def intersect(x,y):
        return x | y
    
    def search_relation(datas):
        dic_values = reduce(intersect, datas.values())
        data = {}
        for i in dic_values:
            dict_key = list()
            for k,v in datas.items():
                if i in v:
                    dict_key.append(k)
    
            if '_'.join(dict_key) in data:
                data['_'.join(dict_key)].add(i)
            else:
                dict_value = set()
                dict_value.add(i)
                data['_'.join(dict_key)] = dict_value
        print(data)
    
    if __name__ == '__main__':
        all_data = {'aa': {1, 2, 3, 5}, 'bb': {2, 3, 4, 5}, 'cc': {3, 4, 5}}
        search_relation(all_data)
    

    相关文章

      网友评论

          本文标题:Python字典相同值的键合并

          本文链接:https://www.haomeiwen.com/subject/skntectx.html