Pythoner1234 Pythoner1234 - 3 months ago 9
Python Question

How to delete a dictionary in a list, if the same dictionary is in another list (Python 2.7)

I have two lists that include same dictionaries in the format of:

List 1:

[{'url': u'http://www.bloomberg.com/news/articles/2016-08-17/you-can-get-a-50-phone-from-amazon-if-you-don-t-mind-the-ads','title': u'You Can Get a $50 Phone From Amazon, If You Don\u2019t Mind the Ads'}, {'url': u'http://www.bloomberg.com/news/features/2016-08-18/uber-s-first-self-driving-fleet-arrives-in-pittsburgh-this-month-is06r7on', 'title': u'Uber\u2019s First Self-Driving Fleet Arrives in Pittsburgh This Month'}]


List 2:

[{'url': u'http://www.bloomberg.com/news/articles/2016-08-17/you-can-get-a-50-phone-from-amazon-if-you-don-t-mind-the-ads', 'title': u'You Can Get a $50 Phone From Amazon, If You Don\u2019t Mind the Ads'}]


What I wanted to do:
I would like to delete the dictionary(both url and title) in list 2 from the one in list 1.

I have tried this, but couldn't manage to do it.

list1[:] = [d for d in list1 if d.get('title') != (fail for fail in list2 if fail.get('title'))]


Result:

list1 = [{'url': u'http://www.bloomberg.com/news/features/2016-08-18/uber-s-first-self-driving-fleet-arrives-in-pittsburgh-this-month-is06r7on', 'title': u'Uber\u2019s First Self-Driving Fleet Arrives in Pittsburgh This Month'}]

Answer

Just do a simple comparison:

>>> final = [i for i in one if i not in two]
>>> final
[{'url': u'http://www.bloomberg.com/news/features/2016-08-18/uber-s-first-self-driving-fleet-arrives-in-pittsburgh-this-month-is06r7on', 'title': u'Uber\u2019s First Self-Driving Fleet Arrives in Pittsburgh This Month'}]

Then you can do list1 = final if you really want.