具有相同键的Python字典

2 python data-structures

我有一个包含字典的python列表,我想创建一个新列表,其中包含带有唯一键和相关列表值的字典,如下所示:

Input:
 [{1: 2}, {2: 2}, {1: 3}, {2: 1}, {1: 3}]
Output:
 [{1:[2,3,3]},{2:[2,1]}]
Run Code Online (Sandbox Code Playgroud)

提前致谢.

Pau*_*ine 7

怎么样:

input = [{1: 2}, {2: 2}, {1: 3}, {2: 1}, {1: 3}]

r = {}
for d in input:
    # (assumes just one key/value per dict)
    ((x, y),) = d.items() 
    r.setdefault(x, []).append(y)

print [ {k: v} for (k, v) in r.items() ]
Run Code Online (Sandbox Code Playgroud)

结果:

[{1: [2, 3, 3]}, {2: [2, 1]}]
Run Code Online (Sandbox Code Playgroud)

[更新]

只是好奇:你在什么回事解释((x, y),) = d.items()r.setdefault(x, []).append(y)?- 该死的

首先是((x, y),) = d.items():

  • 在这一点上,d将是一个元素input,就像{1: 2}
  • d.items() 将是类似的东西 [(1, 2)]
  • 为了将1和2解包为x和y,我们需要额外的,(否则解释器会认为外括号正在进行分组而不是定义单个元素元组)

r.setdefault(x, []).append(y)类似于:

if not r.has_key(x):
     r[x] = []
r[x].append(y)
Run Code Online (Sandbox Code Playgroud)