Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove elements from a Python dictionary based on elements in a list?

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')}
like image 579
CiaranWelsh Avatar asked Dec 15 '22 09:12

CiaranWelsh


1 Answers

I would use a dictionary comprehension to map the keys with the values that aren't found within a list:

new_dict = {k: v for k, v in old_dict.items() if v not in the_list} # filter from the list
like image 144
Malik Brahimi Avatar answered Dec 16 '22 22:12

Malik Brahimi