当它们的键具有值列表时合并多个字典 [英] Merge multiple dictionaries when their keys have a list of values Python

查看:68
本文介绍了当它们的键具有值列表时合并多个字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当每本字典的每个键都有一个值列表时,我遇到了一个帖子,该帖子具有完整且正确的方式合并两个字典的方式.

I came across a post that had a complete and correct way of merging two dictionaries, when each dictionary has for each key a list of values.

程序的输入如下:

d1:  {'apple': ['5', '65'], 'blue': ['9', '10', '15', '43'], 'candle': ['15'], 'is': ['5', '6', '13', '45', '96'], 'yes': ['1', '2', '3', '11'], 'zone': ['5', '6', '9', '10', '12', '14', '18', '19', '23', '24', '25', '29', '45']}
d2:  {'apple': ['43', '47'], 'appricote': ['1', '2', '3', '4', '5', '6'], 'candle': ['1', '2', '4', '5', '6', '9'], 'delta': ['14', '43', '47'], 'dragon': ['23', '24', '25', '26'], 'eclipse': ['11', '13', '15', '19'], 'island': ['1', '34', '35']}

合并功能的代码为:

def merge_dictionaries(dict1, dict2):

result = {}
new_result = {}
for key in set().union(*(dict1, dict2)):
    result[key] = sorted(dict1.get(key, []) + dict2.get(key, []), key=int)
    # Delete any double value for each key
    new_result[key] = [ii for n, ii in enumerate(result[key]) if ii not in result[key][:n]]

return new_result

结果:

Merged:  {'is': ['5', '6', '13', '45', '96'], 'dragon': ['23', '24', '25', '26'], 'apple': ['5', '43', '47', '65'], 'appricote': ['1', '2', '3', '4', '5', '6'], 'delta': ['14', '43', '47'], 'eclipse': ['11', '13', '15', '19'], 'yes': ['1', '2', '3', '11'], 'zone': ['5', '6', '9', '10', '12', '14', '18', '19', '23', '24', '25', '29', '45'], 'blue': ['9', '10', '15', '43'], 'island': ['1', '34', '35'], 'candle': ['1', '2', '4', '5', '6', '9', '15']}

我现在想要实现的是扩展这种方式来合并动态数量的此类字典.这是我的尝试,我每次都会从"dicts"列表中获得2个项目,然后尝试将它们合并.

What I want to achieve now is to extend this way for merging a dynamic number of dictionaries of this kind.This is my try in which I get from the list of "dicts" 2 items each time and try to merge them.

def merge_multiple_dictionaries(dicts):
''' This is just to print the input I get
l = len(dicts)
print("Len of dicts: ", l)
for j in range(0, l):
    print("j is: ", dicts[j])
'''
result = {}
new_result = {}
for k in range(0, l):
     if k is (len(dicts)-1):
        break
    print("k: ", k)
    for key in set().union(*(dicts[k], dicts[k+1])):
        result[key] = sorted(dicts[k].get(key, []) + dicts[k+1].get(key, []), key=int)
        # Delete any double value for each key
        new_result[key] = [ii for n, ii in enumerate(result[key]) if ii not in result[key][:n]]
# result = OrderedDict(sorted([(k, v) for k, v in result.items()]))

return new_result

那么还有一种更Python化的方法来实现这一目标吗?

So is there a more pythonic way to achieve that?

推荐答案

由于set().union()操作可以使用多个参数,因此无需遍历字典对.

There is no need to iterate over pairs of dictionaries, as set().union() operation can take multiple arguments:

def merge_dictionaries(*args):
    result = {}
    for key in set().union(*args):
        # let's convert the value union to set before sorting to get rid of the duplicates
        result[key] = sorted(set.union(*[set(d.get(key, [])) for d in args]), key=int)
    return result

这篇关于当它们的键具有值列表时合并多个字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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