简体   繁体   English

如何按唯一键值合并字典列表

[英]How to merge list of dictionaries by unique key value

I want to merge list of dictionary provided below with unique channel and zrepcode.我想将下面提供的字典列表与唯一频道和 zrepcode 合并。

sample input:样本输入:

[
  {
    "channel": 1,
    "zrepcode": "123456",
    "turn": 7833.9
  },
  {
    "channel": 1,
    "zrepcode": "123456",
    "pipeline": 324
  },
  {
    "channel": 1,
    "zrepcode": "123456",
    "inv_bal": 941.16
  },
  {
    "channel": 1,
    "zrepcode": "123456",
    "display": 341
  },
  {
    "channel": 3,
    "zrepcode": "123456",
    "display": 941.16
  },
  {
    "channel": 3,
    "zrepcode": "123456",
    "turn": 7935.01
  },
  {
    "channel": 3,
    "zrepcode": "123456",
    "pipeline": 0
  },
  {
    "channel": 3,
    "zrepcode": "123456",
    "inv_bal": 341
  },
  {
    "channel": 3,
    "zrepcode": "789789",
    "display": 941.16
  },
  {
    "channel": 3,
    "zrepcode": "789789",
    "turn": 7935.01
  },
  {
    "channel": 3,
    "zrepcode": "789789",
    "pipeline": 0
  },
  {
    "channel": 3,
    "zrepcode": "789789",
    "inv_bal": 341
  }
]

Sample output:样品 output:

[
{'channel': 1, 'zrepcode': '123456', 'turn': 7833.9, 'pipeline': 324.0,'display': 341,'inv_bal': 941.16},
{'channel': 3, 'zrepcode': '123456', 'turn': 7935.01, 'pipeline': 0.0, 'display': 941.16, 'inv_bal': 341.0},
{'channel': 3, 'zrepcode': '789789', 'turn': 7935.01, 'pipeline': 0.0, 'display': 941.16, 'inv_bal': 341.0}
]

Easily solved with our good friend collections.defaultdict :我们的好朋友collections.defaultdict轻松解决:

import collections


by_key = collections.defaultdict(dict)

for datum in data:  # data is the list of dicts from the post
    key = (datum.get("channel"), datum.get("zrepcode"))  # form the key tuple
    by_key[key].update(datum)  # update the defaultdict by the key tuple

print(list(by_key.values()))

This outputs这输出

[
  {'channel': 1, 'zrepcode': '123456', 'turn': 7833.9, 'pipeline': 324, 'inv_bal': 941.16, 'display': 341},
  {'channel': 3, 'zrepcode': '123456', 'display': 941.16, 'turn': 7935.01, 'pipeline': 0, 'inv_bal': 341},
  {'channel': 3, 'zrepcode': '789789', 'display': 941.16, 'turn': 7935.01, 'pipeline': 0, 'inv_bal': 341},
]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM