Python字典相同值的键合并

2019-08-23  本文已影响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)
上一篇下一篇

猜你喜欢

热点阅读