0

let's assume we have a dictionary 'd' with key '1' and the value of '1' is a list '[11,22,33,44]' then how can we remove all values less than 30?

I tried to run a loop and use the remove function:

d={1:[11,22,33,44]}
for j in d[1]:
    if j<=30:
        d[1].remove(j)
print(d)

the result I was expecting was: {1: [33, 44]} but instead after removing the 1st element the loop stopped and gave me: {1: [22, 33, 44]}

2 Answers2

2

This is a classic problem of removing items from a list

When you remove item #0, everything else shuffles up, so that the old item #1 moves into place #0.

On the next iteration, the loop looks at the new #1. Therefore the original #1 escapes the testing!

You could work backwards through the list

That is the standard solution for most programming languages.

The more pythonic solution is to recreate the list without the unwanted elements

Python's list comprehensions are designed to make this very easy:

d={1:[11,22,33,44]}

d[1]=[element for element in d[1] if element>30]

print(d)

ProfDFrancis
  • 8,816
  • 1
  • 17
  • 26
0

Do not modify a list when iterating over it. Better to reconstruct the list as follows:

d = {
    1: [11,22,33,44]
}
d[1] = [n for n in d[1] if n >= 30]
print(d)

Output:

{1: [33, 44]}
DarkKnight
  • 19,739
  • 3
  • 6
  • 22