【问题标题】:How to merge elements of dictionary with elements of list of lists of dictionaries?如何将字典的元素与字典列表的元素合并?
【发布时间】:2021-08-11 17:25:45
【问题描述】:

我的列表中有一本字典:

[{'selectionId': 47999}, {'selectionId': 55190}, {'selectionId': 58805}]

还有一个字典列表:

[[{'price': 2.04, 'size': 45.35}, {'price': 2.02, 'size': 7404.31}, {'price': 2.0, 'size': 15485.06}], [{'price': 4.3, 'size': 2493.19}, {'price': 4.2, 'size': 5627.74}, {'price': 4.1, 'size': 1489.93}], [{'price': 3.5, 'size': 5785.37}, {'price': 3.45, 'size': 4404.69}, {'price': 3.4, 'size': 4917.9}]]

我想用列表列表的字典中的每个元素“压缩”第一个字典的元素,如下所示:

[[{'selectionId': 47999, 'price': 2.04, 'size': 45.35}, {'selectionId': 47999, 'price': 2.02, 'size': 7404.31}, {'selectionId': 47999, 'price': 2.0, 'size': 15485.06}]...

等等。我怎么能这样做?我已经尝试了{**x, **y} 语法,但没有按照我想要的方式工作。

【问题讨论】:

  • Stackoverflow 不是免费的编码服务。您应该发送honest attempt at the solution,然后然后在必要时询问有关它的具体问题。

标签: python dictionary merge zip


【解决方案1】:
from pprint import pprint

l1 = [{"selectionId": 47999}, {"selectionId": 55190}, {"selectionId": 58805}]
l2 = [
    [
        {"price": 2.04, "size": 45.35},
        {"price": 2.02, "size": 7404.31},
        {"price": 2.0, "size": 15485.06},
    ],
    [
        {"price": 4.3, "size": 2493.19},
        {"price": 4.2, "size": 5627.74},
        {"price": 4.1, "size": 1489.93},
    ],
    [
        {"price": 3.5, "size": 5785.37},
        {"price": 3.45, "size": 4404.69},
        {"price": 3.4, "size": 4917.9},
    ],
]

for a, b in zip(l1, l2):
    for d in b:
        d.update(a)

pprint(l2)

打印:

[[{'price': 2.04, 'selectionId': 47999, 'size': 45.35},
  {'price': 2.02, 'selectionId': 47999, 'size': 7404.31},
  {'price': 2.0, 'selectionId': 47999, 'size': 15485.06}],
 [{'price': 4.3, 'selectionId': 55190, 'size': 2493.19},
  {'price': 4.2, 'selectionId': 55190, 'size': 5627.74},
  {'price': 4.1, 'selectionId': 55190, 'size': 1489.93}],
 [{'price': 3.5, 'selectionId': 58805, 'size': 5785.37},
  {'price': 3.45, 'selectionId': 58805, 'size': 4404.69},
  {'price': 3.4, 'selectionId': 58805, 'size': 4917.9}]]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-16
    • 1970-01-01
    • 2019-02-24
    • 1970-01-01
    • 2017-10-17
    • 1970-01-01
    • 2023-03-05
    • 1970-01-01
    相关资源
    最近更新 更多