假设我有两个字典列表:
a=[{'name':'A','color':'1'},
{'name':'B','color':'2'}]
b=[{'name':'A','color':'3'},
{'name':'c','color':'1'}]
我需要这样的东西:
for i in a:
if i['name'] is not existent in b['name']:
do this.
else:
if i['color'] is < than the corresponding item in b list:
do that.
我不知道如何从导致迭代继续“else:”的第二个列表中获取元素。
我需要说的是第一个列表较小(几百个条目)但是第二个有几千个词典,每个词典大约有一百个条目-效率非常重要。
我确实考虑过为两个列表中的键 ['name'] 制作一个所有值的列表并进行比较,但这意味着第一次迭代以制作这些列表然后重复列表以执行此操作或去做。 提前致谢!
最佳答案
你绝对想在开始之前对 b
进行迭代。唯一明显的替代方法是为 a
中的每个 项迭代b
,这显然更糟。
b_dict = {x['name']: x for x in b}
for item in a:
if item['name'] in b_dict:
f(b_dict['name'])
else:
pass # whatever
如果您希望避免使用 in
后立即获取元素,您可能对 Python 字典的 get()
方法感兴趣。
关于python - 比较两个字典列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43063054/