【问题标题】:how to add a dictionary item from one list to the other dictionary in other list如何将一个列表中的字典项添加到另一个列表中的另一个字典
【发布时间】:2019-12-19 15:28:25
【问题描述】:

我有一个这样的字典列表:

data = [{"name":"Kane", "age": 29},
        {"name":"will", "age": "32"}]


dtat_2 = [ {"Team":"SRH", "Country" :"NZ"},
           {"Team":"RCB", "Country" :"WI"}]

预期输出:

data3 = [{"name":"Kane", "age": 29, "Team":"SRH", "Country" :"NZ"},
         {"name":"will", "age": "32", "Team":"RCB", "Country" :"WI"}]

我该怎么做?

【问题讨论】:

标签: python python-3.x


【解决方案1】:

在 python >= 3.5 上,您可以像这样压缩列表并解压它们:

[{**d1, **d2} for d1, d2 in zip(data, dtat_2)]
# [{'Country': 'NZ', 'Team': 'SRH', 'age': 29, 'name': 'Kane'},
#  {'Country': 'WI', 'Team': 'RCB', 'age': '32', 'name': 'will'}]

另一个适用于任何版本的方法是就地更新,这会更新其中一个字典(仅供参考)。

for d1, d2 in zip(data, dtat_2):
    d1.update(d2)

data
# [{'Country': 'NZ', 'Team': 'SRH', 'age': 29, 'name': 'Kane'},
#  {'Country': 'WI', 'Team': 'RCB', 'age': '32', 'name': 'will'}]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-13
    • 2021-06-08
    • 2022-06-23
    • 1970-01-01
    • 2021-11-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多