合并字典保留重复键的值 [英] Merge dictionaries retaining values for duplicate keys

查看:79
本文介绍了合并字典保留重复键的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



例如:


给定n个字典,写一个函数,返回一个唯一的字典,其中包含重复键的值列表。

  d1 = {'a':1,'b':2} 
d2 = {'c':3,'b':4}
d3 = {'a':5,'d':6}

 >>> newdict 
{'c':3,'d':6,'a':[1,5],'b':[2,4]}
/ pre>

我的代码到目前为止:

 >> > def merge_dicts(* dicts):
... x = []
...针对项目中的项目:
... x.append(item)
... return x
...
>>> merge_dicts(d1,d2,d3)
[{'a':1,'b':2},{'c':3,'b':4},{'a':5,'d ':6}]

什么是最好的方法来生成一个新的字典,产生一个列表

解决方案

  def merge_dicts(* dicts):
d = {}
for dict in dicts:
for key in dict:
try:
d [key] .append(dict [key])
除了KeyError:
d [key] = [dict [key]]
return d

retuns:

  {'a':[1,5],'b':[2,4],'c' :[3],'d':[6]} 

问题略有不同。这里所有的字典值都是列表。如果长度为1的列表不是需要的话,那么在d中添加:


  len(d [key])== 1:
d [key] = d [key] [0]

之前的返回d 语句。但是,我想不想想要删除列表。 (考虑您将列表作为值的情况;然后删除项目周围的列表会导致模糊的情况。)


Given n dictionaries, write a function that will return a unique dictionary with a list of values for duplicate keys.

Example:

d1 = {'a': 1, 'b': 2}
d2 = {'c': 3, 'b': 4}
d3 = {'a': 5, 'd': 6}

result:

>>> newdict
{'c': 3, 'd': 6, 'a': [1, 5], 'b': [2, 4]}

My code so far:

>>> def merge_dicts(*dicts):
...     x = []
...     for item in dicts:
...         x.append(item)
...     return x
...
>>> merge_dicts(d1, d2, d3)
[{'a': 1, 'b': 2}, {'c': 3, 'b': 4}, {'a': 5, 'd': 6}]

What would be the best way to produce a new dictionary that yields a list of values for those duplicate keys?

解决方案

def merge_dicts(*dicts):
    d = {}
    for dict in dicts:
        for key in dict:
            try:
                d[key].append(dict[key])
            except KeyError:
                d[key] = [dict[key]]
    return d

This retuns:

{'a': [1, 5], 'b': [2, 4], 'c': [3], 'd': [6]}

There is a slight difference to the question. Here all dictionary values are lists. If that is not to be desired for lists of length 1, then add:

    for key in d:
        if len(d[key]) == 1:
            d[key] = d[key][0]

before the return d statement. However, I cannot really imagine when you would want to remove the list. (Consider the situation where you have lists as values; then removing the list around the items leads to ambiguous situations.)

这篇关于合并字典保留重复键的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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