簡體   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