python - 使用多个键合并 python 字典列表

标签 python dictionary merge

我想使用多个键合并两个字典列表。

我有一个包含一组结果的字典列表:

l1 = [{'id': 1, 'year': '2017', 'resultA': 2},
      {'id': 2, 'year': '2017', 'resultA': 3},
      {'id': 1, 'year': '2018', 'resultA': 3},
      {'id': 2, 'year': '2018', 'resultA': 5}]

还有另一组结果的另一个字典列表:

l2 = [{'id': 1, 'year': '2017', 'resultB': 5},
      {'id': 2, 'year': '2017', 'resultB': 8},
      {'id': 1, 'year': '2018', 'resultB': 7},
      {'id': 2, 'year': '2018', 'resultB': 9}]

我想使用“id”和“year”键组合它们以获得以下内容:

all = [{'id': 1, 'year': '2017', 'resultA': 2, 'resultB': 5},
       {'id': 2, 'year': '2017', 'resultA': 3, 'resultB': 8},
       {'id': 1, 'year': '2018', 'resultA': 3, 'resultB': 7},
       {'id': 2, 'year': '2018', 'resultA': 5, 'resultB': 9}]

我知道要在一个键上组合两个字典列表,我可以使用这个:

l1 = {d['id']:d for d in l1} 

all = [dict(d, **l1.get(d['id'], {})) for d in l2]  

但它忽略了年份,提供了以下不正确的结果:

all = [{'id': 1, 'year': '2018', 'resultA': 3, 'resultB': 5},
       {'id': 2, 'year': '2018', 'resultA': 5, 'resultB': 8},
       {'id': 1, 'year': '2018', 'resultA': 3, 'resultB': 7},
       {'id': 2, 'year': '2018', 'resultA': 5, 'resultB': 9}]

像在 R 中一样处理它,通过添加我要合并的第二个变量,我得到一个 KeyError:

l1 = {d['id','year']:d for d in l1} 

all = [dict(d, **l1.get(d['id','year'], {})) for d in l2]   

如何使用多个键进行合并?

最佳答案

代替 d['id','year'],使用元组 (d['id'], d['year']) 作为你的键。

关于python - 使用多个键合并 python 字典列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49997558/

相关文章:

python - 类型错误 : ufunc 'subtract' did not contain a loop with signature matching types dtype ('<U8' ) dtype ('<U8' ) dtype ('<U8' )

java - dockerfile 中的 python 路径

python - 记录同一函数的不同参数可能性

python - 第一次写入 CSV 文件后跳过标题(Python)

java - 我想在我的 Java 代码中将多个映射值存储在 Redis 的单个键中

Python:将字典转换为字节

python - 字典值缺失

Git merge 测试分支(最终提交)到 master 分支

java - 如何在 Java 中合并两个 XML

PHP 在空值上合并数组