繁体   English   中英

从两个不同列表中的字典中删除重复键/值的更多pythonic方法

[英]More pythonic way to remove duplcate key/values from dict inside two diferent lists

使用python 2.7,什么是只返回与两个不同列表上的一组字典不同的东西的正确方法? 下面的代码是可行的,但是我确定有更好的方法可以做到,但是我不确定如何实现。

l_current = [{'type': 'food', 'drink': 'water'},{'type': 'food', 'drink': 'other'}]
l_new = [{'type': 'food', 'drink': 'other'},
         {'type': 'food', 'drink': 'dirt'},
         {'type': 'food', 'drink': 'gasoline'}]
l_final = []
for curr in l_current:
    for new in l_new:
        nkey = new['propertie_key']
        ckey = curr['propertie_key']
        nval = new['propertie_value']
        cval = curr['propertie_value']
        if nkey == ckey:
            if nval != cval:
                d_final = {nkey: nval}
                l_final.append(d_final)

所需的输出与l_current的区别在于l_new:

[{'type': 'food', 'drink': 'dirt'},{'type': 'food', 'drink': 'gasoline'}]

编辑:这不是一项作业,我只是在尝试优化当前的工作代码。

编辑2:所需的输出已经存在,在google上进行一些搜索后,我能够找到一些类似于以下解决方案的解决方案,但是我不确定如何实现。

在Python列表中删除重复的字典

如何从字典中减去值

如果我正确理解这一点,就这么简单:

l_current = [{'type': 'food', 'drink': 'water'},{'type': 'food', 'drink': 'other'}]
l_new = [{'type': 'food', 'drink': 'other'},
         {'type': 'food', 'drink': 'dirt'},
         {'type': 'food', 'drink': 'gasoline'}]

l_final = [x for x in l_new if x not in l_current]
print(l_final)  # [{'drink': 'dirt', 'type': 'food'}, {'drink': 'gasoline', 'type': 'food'}]

您可以使用与比较Python中其他任何对象相同的方式来比较字典,这就是上面的列表理解起作用的原因; 对成员资格的测试归结为对等性检查

从给定的示例中,您可以通过列表理解获得所需的结果:

l_final = [item for item in l_new if item not in l_current]

这应该检查新列表中的每个项目,如果当前列表元素不存在,则将其存储在最终列表中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM