在python中合并字典值列表

bra*_*n85 14 python merge dictionary list

我正在尝试合并三个词典,它们都具有相同的键,以及值列表或单个值.

one={'a': [1, 2], 'c': [5, 6], 'b': [3, 4]}
two={'a': [2.4, 3.4], 'c': [5.6, 7.6], 'b': [3.5, 4.5]}
three={'a': 1.2, 'c': 3.4, 'b': 2.3}
Run Code Online (Sandbox Code Playgroud)

我需要的是将值中的所有项添加到一个列表中.

result={'a': [1, 2, 2.4, 3.4, 1.2], 'c': [5, 6, 5.6, 7.6, 2.3], 'b': [3, 4, 3.5, 4.5, 3.4]}
Run Code Online (Sandbox Code Playgroud)

我尝试了几件事,但大多数都将值放入嵌套列表中.例如

out=dict((k, [one[k], two.get(k), three.get(k)]) for k in one)
{'a': [[1, 2], [2.4, 3.4], 1.2], 'c': [[5, 6], [5.6, 7.6], 3.4], 'b': [[3, 4], [3.5, 4.5], 2.3]}
Run Code Online (Sandbox Code Playgroud)

我尝试通过循环遍历值来更新它:

out.update((k, [x for x in v]) for k,v in out.iteritems())
Run Code Online (Sandbox Code Playgroud)

但结果完全一样.我试图简单地添加列表,但因为第三个字典只有一个浮点数,我无法做到.

check=dict((k, [one[k]+two[k]+three[k]]) for k in one)
Run Code Online (Sandbox Code Playgroud)

所以我尝试首先将值添加到一个和两个值中,然后追加三个值.添加列表运行良好,但是当我尝试从第三个字典追加浮点数时,突然整个值变为'无'

check=dict((k, [one[k]+two[k]]) for k in one)
{'a': [[1, 2, 2.4, 3.4]], 'c': [[5, 6, 5.6, 7.6]], 'b': [[3, 4, 3.5, 4.5]]}
new=dict((k, v.append(three[k])) for k,v in check.items())
{'a': None, 'c': None, 'b': None}
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 19

作为一个单行,具有字典理解:

new = {key: value + two[key] + [three[key]] for key, value in one.iteritems()}
Run Code Online (Sandbox Code Playgroud)

这将创建新列表,将列表one与相应列表连接起来two,将单个值three放入临时列表中以使连接更容易.

或者使用就地for更新循环one:

for key, value in one.iteritems():
    value.extend(two[key])
    value.append(three[key])
Run Code Online (Sandbox Code Playgroud)

这用于使用list.extend()列表从原位更新原始列表two,并list.append()从中添加单个值three.

哪里出错了:

  • 您的第一次尝试使用来自的值创建一个新列表one,twothree嵌套在现有列表中,而不是连接现有列表.您尝试清理它只是复制了那些嵌套列表.

  • 您的第二次尝试不起作用,因为值three不是列表,因此无法连接.我为这一个值创建了一个新列表.

  • 您的最后一次尝试不应该list.append()在生成器表达式中使用,因为您存储该方法的返回值,该值始终是None(其更改v直接存储,并且列表不需要再次返回).

演示第一种方法:

>>> one={'a': [1, 2], 'c': [5, 6], 'b': [3, 4]}
>>> two={'a': [2.4, 3.4], 'c': [5.6, 7.6], 'b': [3.5, 4.5]}
>>> three={'a': 1.2, 'c': 3.4, 'b': 2.3}
>>> {key: value + two[key] + [three[key]] for key, value in one.iteritems()}
{'a': [1, 2, 2.4, 3.4, 1.2], 'c': [5, 6, 5.6, 7.6, 3.4], 'b': [3, 4, 3.5, 4.5, 2.3]}
Run Code Online (Sandbox Code Playgroud)

  • 对于“python3”,使用“items()”而不是“iteritems()” (7认同)

jpp*_*jpp 16

任意字典编号和键

@MartijnPieters 的解决方案涵盖了您尝试的问题。

对于通用解决方案,请考虑使用itertools.chain链接多个字典。您还可以将 adefaultdict用于更一般的情况,即您在每个字典中找不到相同的键。

from collections import defaultdict
from itertools import chain
from operator import methodcaller

# dictionaries with non-equal keys, values all lists for simplicity
one = {'a': [1, 2], 'c': [5, 6], 'b': [3, 4], 'e': [6.2]}
two = {'a': [2.4, 3.4], 'c': [5.6, 7.6], 'b': [3.5, 4.5], 'f': [1.3]}
three = {'a': [1.2], 'c': [3.4], 'b': [2.3], 'e': [3.1]}

# initialise defaultdict of lists
dd = defaultdict(list)

# iterate dictionary items
dict_items = map(methodcaller('items'), (one, two, three))
for k, v in chain.from_iterable(dict_items):
    dd[k].extend(v)

print(dd)

# defaultdict(list,
#             {'a': [1, 2, 2.4, 3.4, 1.2],
#              'b': [3, 4, 3.5, 4.5, 2.3],
#              'c': [5, 6, 5.6, 7.6, 3.4],
#              'e': [6.2, 3.1],
#              'f': [1.3]})
Run Code Online (Sandbox Code Playgroud)

Notedefaultdict是 的子类,dict因此通常不需要将结果转换为常规dict.


小智 5

一个强大的解决方案。=)

def FullMergeDict(D1, D2):
  for key, value in D1.items():
    if key in D2:
      if type(value) is dict:
        FullMergeDict(D1[key], D2[key])
      else:
        if type(value) in (int, float, str):
          D1[key] = [value]
        if type(D2[key]) is list:
          D1[key].extend(D2[key])
        else:
          D1[key].append(D2[key])
  for key, value in D2.items():
    if key not in D1:
      D1[key] = value

if __name__ == '__main__':
  X = {
    'a': 'aaa',
    'c': [1,3,5,7],
    'd': 100,
    'e': {'k': 1, 'p': 'aa','t': [-1,-2]},
    'f': {'j':1}
  }
  Y = {
    'b': 'bbb',
    'd': 200,
    'e': {'k': 2, 'p': 'bb','o': [-4]},
    'c': [2,4,6],
    'g': {'v':2}
  }
  FullMergeDict(X, Y)
  exit(0)
Run Code Online (Sandbox Code Playgroud)

结果:

  X = {
    'a': 'aaa',
    'b': 'bbb',
    'c': [1, 3, 5, 7, 2, 4, 6],
    'd': [100, 200],
    'e': {'k': [1, 2], 'o': [-4], 'p': ['aa', 'bb'], 't': [-1, -2]},
    'f': {'j': 1},
    'g': {'v': 2}}
Run Code Online (Sandbox Code Playgroud)