-3

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?

Imran
  • 71
  • 5

3 Answers3

2

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]}
Timeless
  • 22,580
  • 4
  • 12
  • 30
0

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.

marmeladze
  • 6,468
  • 3
  • 24
  • 45
0

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]}
DarkKnight
  • 19,739
  • 3
  • 6
  • 22