Ad
How To Remove Duplicate Dictionary Based On Selected Keys From A List Of Dictionaries In Python?
I am new to Python and trying to learn it as much as possible. I am stuck with a silly problem where I want to remove certain dictionary items of a list based on selective key-value pairs. For ex, I have:
l = [{'A':1, 'B':2, 'C':3, 'D':4},
{'A':5, 'B':6, 'C':7, 'D':8},
{'A':1, 'B':9, 'C':3, 'D':10}]
And the output I want is removal of dictionaries based on two keys A
and C
values:
l = [{'A':1, 'B':2, 'C':3, 'D':4},
{'A':5, 'B':6, 'C':7, 'D':8}]
Ad
Answer
Using set
to remember whether the items are seen.
>>> A, B, C, D = 'ABCD'
>>>
>>> lst = [
... {A:1, B:2, C:3, D:4},
... {A:5, B:6, C:7, D:8},
... {A:1, B:9, C:3, D:10}
... ]
>>> seen = set()
>>> [x for x in lst if [(x[A], x[C]) not in seen, seen.add((x[A], x[C]))][0]]
[{'A': 1, 'C': 3, 'B': 2, 'D': 4}, {'A': 5, 'C': 7, 'B': 6, 'D': 8}]
Ad
source: stackoverflow.com
Related Questions
- → What are the pluses/minuses of different ways to configure GPIOs on the Beaglebone Black?
- → Django, code inside <script> tag doesn't work in a template
- → React - Django webpack config with dynamic 'output'
- → GAE Python app - Does URL matter for SEO?
- → Put a Rendered Django Template in Json along with some other items
- → session disappears when request is sent from fetch
- → Python Shopify API output formatted datetime string in django template
- → Can't turn off Javascript using Selenium
- → WebDriver click() vs JavaScript click()
- → Shopify app: adding a new shipping address via webhook
- → Shopify + Python library: how to create new shipping address
- → shopify python api: how do add new assets to published theme?
- → Access 'HTTP_X_SHOPIFY_SHOP_API_CALL_LIMIT' with Python Shopify Module
Ad