Reputation: 433
I have a dictionary with list as its values, like this:
{"a":[1,2,3,4,5],"b":[6,7,8,9,10]}
How do I remove certain element from the dictionary values? For example, removing element 3
from key a
will result: {"a":[1,2,4,5],"b":[6,7,8,9,10]}
I am using Python version 3.9.1.
Upvotes: 1
Views: 44
Reputation: 71560
Try using a dictionary comprehension:
dct = {"a": [1, 2, 3, 4, 5], "b": [6, 7, 8, 9, 10]}
print({k: [i for i in v if v != 3] for k, v in dct.items()})
Output:
{'a': [1, 2, 4, 5], 'b': [6, 7, 8, 9, 10]}
I iterate through the dictionary by key and value, I don't modify the keys, but I modify the values by iterating through the lists of each value, and only keep the list values if they aren't 3
.
Edited:
As the OP said in the comments, he wants to only remove the 3
s from the a
key.
So try this:
dct = {"a": [1, 2, 3, 4, 5], "b": [1, 2, 3, 4, 5]}
print({k: (v if k != 'a' else [i for i in v if i != 3]) for k, v in dct.items()})
Output:
{"a": [1, 2, 4, 5], "b": [1, 2, 3, 4, 5]}
Upvotes: 2