Remove element in list in a dictionary from specific keys

61 Views Asked by At

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?

3

There are 3 best solutions below

0
Timeless On BEST ANSWER

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]}
0
marmeladze On

An ugly comprehension like that,

{k: [n for n in my_dict[k] if not n<3] for k in my_dict if k != 'B'} 

will give you desired output.

0
SIGHUP On

Here's an inclusive approach - i.e., we're interested in keys A and C. B would be implicitly ignored as would any other keys (apart from A and C)

my_dict = {'A' : [1, 2, 3, 4, 5], 'B' : [10, 1, 2, 5, 8], 'C': [6, 5, 3, 1]}

for key in 'AC':
    my_dict[key] = [n for n in my_dict[key] if n > 2]

print(my_dict)

Output:

{'A': [3, 4, 5], 'B': [10, 1, 2, 5, 8], 'C': [6, 5, 3]}