【发布时间】:2021-05-14 00:41:18
【问题描述】:
我在 python 中有这么大的字典列表。下面是一个例子:
big_list_dictionary = [{
'name': 'test = 1',
'id': 1,
'value': 30
},{
'name': 'apple = 1',
'id': 2,
'value': 70
},{
'name': 'orange = 1',
'id': 3,
'value': 10
},{
'name': 'balloon = 1',
'id': 4,
'value': 20
},{
'name': 'airplane = 1',
'id': 5,
'value': 40
}]
我有一个包含两个字典及其总值的列表
total1 = [{
'name': 'test',
'total': 130
},{
'name': 'apple',
'total': 270
},{
'name': 'orange',
'total': 310
},{
'name': 'balloon',
'total': 420
},{
'name': 'airplane',
'total': 540
}]
total2 = [{
'name': 'test',
'total': 230
},{
'name': 'apple',
'total': 570
},{
'name': 'orange',
'total': 3210
},{
'name': 'balloon',
'total': 620
},{
'name': 'airplane',
'total': 940
}]
如果您注意到,total1 和 total2 中的 name 与 big_list_dictionary 略有不同,其中 = 1 被省略。
如何将 total1 和 total2 的总值添加到 big_list_dictionary 以便最终结果如下所示:
[{
'name': 'test = 1',
'id': 1,
'value': 30,
'total2': 230,
'total1': 130
},{
'name': 'apple = 1',
'id': 2,
'value': 70,
'total2': 570,
'total1': 270
},{
'name': 'orange = 1',
'id': 3,
'value': 10,
'total2': 3210,
'total1': 310
},{
'name': 'balloon = 1',
'id': 4,
'value': 20,
'total2': 620,
'total1': 420
},{
'name': 'airplane = 1',
'id': 5,
'value': 40,
'total2': 940,
'total1': 540
}]
目前,我这样做的方式很慢。
for item in big_list_dictionary:
for t1,t2 in zip(total1,total2):
if t1['name'] in item['name']:
item['total1] = t1['total']
item['total2'] = t2['total']
我怎样才能有效地做到这一点?
【问题讨论】:
标签: python list dictionary optimization