对字典列表进行分类

时间:2015-03-02 07:58:43

标签: python list dictionary

我有两个dict列表,如下面的Python

L1 = [ {"v1":200,"v2":1},{"v1":300,"v2":2},{"v1":400,"v2":3},{"v1":500,"v2":4} ] 
L2 = [{"v1":200,"v2":1},{"v1":300,"v2":10}]

我想将它们分为3个不同的列表

Rule 1: If L1.V1 == L2.V1 AND L1.V2 == L2.V2 then Identical 
Rule 2: If L1.V1 not in L2.V1 then New
Rule 3:  If L1.V1 == L2.V1 AND L1.V2 != L2.V2 then Updated 

以下是我的代码

           for l1 in L1:
                for l2 in L2:
                    if l1['V1'] == l2['V1']:
                        if l1['V2']  == l2['V2'] :
                            Identicall1.append(l1)
                        elif (l1['V2']  != l2['V2']):
                            updatedl1.append(l1)
                    else:
                        new_l1.append(l1)

它没有按预期工作。我发现它没有检查L2中的所有值。

更新:

比如说:

1) Consider L1[0] and L2[0] both are same by Rule 1. So i want to push L1[0] into identical list 

2) consider L1[1] and L2[0] since the L1[1].V1 != L2[1].V1 skip and move to next in L2
   Compare L2[1] with L1[1] in this case L1[1].V2 != L2[1].V2 so by Rule 2 push this L1[1] into Update list 


3) L1[2].v1 and L1[3].v1 are not in L2 so push to new list 

任何人都可以帮助我。谢谢,

更新

输入

L1 = [ {"v1":200,"v2":1},{"v1":300,"v2":2},{"v1":400,"v2":3},{"v1":500,"v2":4} ] 
    L2 = [{"v1":200,"v2":1},{"v1":300,"v2":10}]

O / p

new_l1= [{"v1":400,"v2":3},{"v1":500,"v2":4} ]
Update =[{"v1":300,"v2":2}]
Identical =[{"v1":200,"v2":1}]

2 个答案:

答案 0 :(得分:1)

我假设您正在考虑比较每个列表中的两个dicts以检查它们是否相同。在这种情况下,你可以这样做:

L1 = [ {"v1":200,"v2":1},{"v1":300,"v2":2},{"v1":400,"v2":3},{"v1":500,"v2":4} ] 
L2 = [{"v1":200,"v2":1},{"v1":300,"v2":10}]

matching_dict = lambda d1, d2: all(key in d2 and d1[key] == d2[key] for key in d1)

if matching_dict(L1[0], L2[0]):
    if matching_dict(L1[1], L2[1])
        print "Identical"
    else:
        print "Updated"
else:
    print "New"

请注意,我们目前正在通过列表中的索引位置检查每个dict,如果超过2个这样的dict检查将使用zip更好的方法:

>>> zip(L1, L2)
[({'v1': 200, 'v2': 1}, {'v1': 200, 'v2': 1}),
 ({'v1': 300, 'v2': 2}, {'v1': 300, 'v2': 10})]

答案 1 :(得分:1)

使用list comprehensions

创建identical列表:

identical = [d for d in L1 if d in L2]

创建update列表:

L2v1s = set([d['v1'] for d in L2])
update = [d for d in L1 if d['v1'] in L2v1s and not d in identical]

创建new列表:

new = [d for d in L1 if not d in identical + update]

如果性能有问题,您可以使用套装来更快地更多

要求使用dict以外的数据类型,因为dict不可用。