【问题标题】:How to merge list of dictionaries by unique key value如何按唯一键值合并字典列表
【发布时间】:2021-12-31 20:09:26
【问题描述】:

我想将下面提供的字典列表与唯一频道和 zrepcode 合并。

样本输入:

[
  {
    "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
  }
]

示例输出:

[
{'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}
]

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    our good friend 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()))
    

    这个输出

    [
      {'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},
    ]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-02-23
      • 1970-01-01
      • 2018-03-27
      • 1970-01-01
      • 2022-12-18
      • 1970-01-01
      • 2021-04-17
      相关资源
      最近更新 更多