Reputation:
I have a dictionary that looks like this
my_dict = {'i': 5, 'citizens': 12, 'you': 344, 'the': 567, 'me': 11, 'states': 22, '': 104, 'in': 156}
and a list that looks like
ignore_words = ['i', 'we', 'you', 'he', 'she', 'it', 'they', 'me', 'us']
I would like to edit the dictionary to remove all the key-value pairs where one of the keys matches an item in the list so I have output that looks like:
my_dict = {'citizens': 12, 'the': 567, 'states': 22, '': 104, 'in': 156}
I've tried
[my_dict.pop(key) for key in ignore_words]
but I get a KeyError
.
What's the best way to do this?
Upvotes: 1
Views: 57
Reputation: 20669
You can use set.difference
on dict.keys
with ignore_list
keys = my_dict.keys() - ignore_words
out = {k: my_dict[k] for k in keys}
# {'': 104, 'in': 156, 'states': 22, 'citizens': 12, 'the': 567}
Upvotes: 1