Skip to main content
 首页 » 编程设计

python之遍历包含字典的两个列表,将匹配附加到第三个列表

2025年05月04日13davidwang456

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

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} 
] 

是否可以遍历两个字典列表,匹配“国家/地区”键,并将任一字典中的所有唯一键附加到第三个列表中创建的新字典中?例如根据上面的内容,第三个列表将包含:

list2and3 = [ 
{'Country': 'Zambia', 'GDP/Pop 2005': 654.055392253311, 'GDP/Pop 2002': 1198.4556066429468} 
] 

我从这样的事情开始:

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

请您参考如下方法:

将第一个列表转换为字典:

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

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

for item in list202: 
    key = item['Country'] 
    if key in d: 
        d[key].update(item) 
    else: 
        d[key] = item 

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

newlist = d.values() 

注意:这个数据结构不是最优的,考虑重新考虑它。