I have a dictionary like below:
my_dict = {'A' : [1, 2, 3, 4, 5], 'B' : [10, 1, 2, 5, 8], 'C': [6, 5, 3, 1]}
I want to remove values less than 3 from "A" and "C" while B remains the same, so the output looks like the below:
my_dict = {'A' : [ 3, 4, 5], 'B' : [10, 1, 2, 5, 8], 'C': [6, 5, 3]}
How to achieve this fast and easy?
I would use a dict/listcomp :
my_dict = {'A' : [1, 2, 3, 4, 5], 'B' : [10, 1, 2, 5, 8], 'C': [6, 5, 3, 1]}
out = {k: [e for e in v if e >= 3] if k != "B" else v
for k, v in my_dict.items()}
#1.29 µs ± 12.4 ns per loop (mean ± std. dev. of 7 runs, 1,000,000 loops each)
Output :
>>> print(out)
{'A': [3, 4, 5], 'B': [10, 1, 2, 5, 8], 'C': [6, 5, 3]}