Imran
Imran

Reputation: 71

Remove element in list in a dictionary from specific keys

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?

Upvotes: -3

Views: 61

Answers (3)

Adon Bilivit
Adon Bilivit

Reputation: 27211

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]}

Upvotes: 0

Timeless
Timeless

Reputation: 37857

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]}

Upvotes: 2

marmeladze
marmeladze

Reputation: 6572

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.

Upvotes: 0

Related Questions