比较两个词典列表

时间:2017-03-28 07:21:44

标签: python list dictionary

假设我有两个词典列表:

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']的所有值的列表并进行比较,但这意味着首次迭代制作这些列表,然后重复列表以执行此操作或去做。 提前谢谢!

4 个答案:

答案 0 :(得分:0)

您可以使用哈希表或类似的内容:

a=[{'name':'A','color':'1'},
   {'name':'B','color':'2'}]
b=[{'name':'A','color':'3'},
   {'name':'c','color':'1'}]

for item in a:
    mach = list(filter(lambda x: x['name'] == item['name'], b))
    if mach:
        if int(item['color']) > int(mach[0]['color']):
            do that
    else:
        do this
<Dict in Python is a kind of hash table amortized O(1) The documention。 然后您可以将代码更改为:

a=[{'name':'A','color':'1'},
   {'name':'B','color':'2'}]
b=[{'name':'A','color':'3'},
   {'name':'c','color':'1'}]

b_dict = {item['name']:item['color'] for item in b}
for item in a:
    if item['name'] in b_dict and int(item['color']) < int(b_dict[item['name']]):
        print 'do this'
    else:
        print 'do that'

答案 1 :(得分:0)

在开始之前,您绝对想要在b上进行迭代。唯一明显的替代方法是对b中的每个项目的a进行迭代,这显然更糟。

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

如果您希望避免使用get(),然后立即获取该元素,您可能会对Python词典的in方法感兴趣。

答案 2 :(得分:0)

首先制作一个索引:

errno

答案 3 :(得分:0)

不是为两个列表创建值列表,而是仅为列表B执行此操作。然后将if条件更改为

if i['name'] is not existent in names_in_b:

您需要检查此方法的性能增益,但是使用此解决方案,您只需要在B上进行一次迭代,然后在A上进行迭代。