I have a list of tuples:
lst=[(6, 'C'), (6, 'H'), (2, 'C'), (2, 'H')]
And a dictionary:
dct={'6C': (6, 'C'), '6H': (6, 'H'), '9D': (9, 'D'), '10D': (10, 'D'), '11S': (11, 'S'), '2C': (2, 'C'), '2H': (2, 'H')}
How can I remove the elements from the dictionary that are in the list? In this example my desired output would be:
dct2={'9D': (9, 'D'), '10D': (10, 'D'), '11S': (11, 'S')}
我会使用字典理解来映射键与列表中找不到的值:
new_dict = {k: v for k, v in old_dict.items() if v not in the_list} # filter from the list
If you're on Python 2 try this:
for key, value in dct.items():
if value in lst:
del dct[key]
EDIT:
A solution that works in both Python 2 and 3:
dict((key, value) for key, value in dct.items() if value not in lst)
Using the valfilter
function from toolz :
from toolz import valfilter
valfilter(lst.__contains__, dct)
I would make the lst
set before filtering out elements, since it is data structure which let's you test if element is present more efficiently.
purge_set = set(lst)
dict(filter(lambda (k, v): v not in purge_set, dct.iteritems()))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.