迭代两个包含字典的列表,将匹配项追加到第三个列表

2024-05-19 07:08:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个包含字典的列表:

list105 = [
{'Country': 'Zimbabwe', 'GDP/Pop 2005': 281.0751453319367}
{'Country': 'Zambia', 'GDP/Pop 2005': 654.055392253311}
{'Country': 'Congo (Dem. Rep.)', 'GDP/Pop 2005': 115.37122637190915}
]

list202 = [
{'Country': 'Vietnam', 'GDP/Pop 2002': 633.4709249146734}
{'Country': 'Zambia', 'GDP/Pop 2002': 1198.4556066429468}
{'Country': 'Vanuatu', 'GDP/Pop 2002': 1788.4344216880352}
]

是否可以迭代两个字典列表,匹配“Country”键,并将两个字典中的所有唯一键附加到第三个列表中创建的新字典中?E、 g.从上往下看,第三个清单将包括:

^{pr2}$

我从以下几点开始:

list2and3 = []
for line in list105:
    for row in list202:
        if line['Country'] == row['Country']:
            #do something and append to list2and3

Tags: in列表for字典linepopcountryrow
3条回答

将第一个列表转换为dict:

d = {x['Country']:x for x in list105}

然后迭代第二个列表并将数据添加到dict中:

^{pr2}$

最后,应用.values()将dict转换回列表:

newlist = d.values()

注意:此数据结构是次优的,请考虑重新考虑。在

你可能想要一个没有循环的更好的解决方案。在

[x for x in list105 for y in list202 if x['Country'] == y['Country'] and x != y and not x.update(y)]

清单综合法可以帮你找到答案,但它可能不是人类友好的。选你喜欢的就行了。在

from copy import deepcopy
list2and3 = []
for line in list105:
    for row in list202:
        if line['Country'] == row['Country']:
            dic = deepcopy(line) # creates a deepcopy of row, so that the
            dic.update(row)      # update operation doesn't affects the original object
            list2and3.append(dic)

print list2and3

输出:

^{pr2}$

相关问题 更多 >

    热门问题