0

can someone repair my code because it ends after it deletes the first dict. The function should delete all dictionaries which value of density is lower than 5.500

Expected output would be:

[{'name': 'Earth', 'Density': 5.513}]

Mine is:

[{'name': 'Earth', 'Density': 5.513}, 
 {'name': 'Venus', 'Density': 5.204}]`

My code:

base = [
    {"name": "Mars", "Density": 5.427},
    {"name": "Earth", "Density": 5.513},
    {"name": "Venus", "Density": 5.204},
]
density = float(input("density? "))

def deletePlanet(density, base):
    for index in range(0, len(base)):
        while base[index]["Density"] < density:
            del base[index]
            return base

print(deletePlanet(density, base))
user2390182
  • 72,016
  • 6
  • 67
  • 89
randomobject123
  • 113
  • 1
  • 2
  • 7
  • 1
    Move the `return` outside the loop? – Tomerikoo Dec 10 '20 at 08:18
  • Does this answer your question? [Remove dictionary from list](https://stackoverflow.com/questions/1235618/remove-dictionary-from-list) also [How to remove items from a list while iterating?](https://stackoverflow.com/questions/1207406/how-to-remove-items-from-a-list-while-iterating) – Tomerikoo Dec 10 '20 at 08:20
  • Also consider changing your list of dicts to a single dict of the form `name: density`. This way it is much easier to remove your wanted items – Tomerikoo Dec 10 '20 at 08:42

3 Answers3

4

Only return after the loop:

def deletePlanet(density, base):
    for index in range(0, len(base)):
        if base[index]["Density"] < density:  # why while?
            del base[index]
    return base

This is however bound to fail, as by the time you reach some of the indexes in your loop, they may no longer exist.

But generally you should never repeatedly remove from a list. Build it from scratch for better time complexity:

def deletePlanet(density, base):
    return [d for d in base if d["Density"] >= density]

If you want to mutate the existing list object, use slice assignment:

def deletePlanet(density, base):
    base[:] = [d for d in base if d["Density"] >= density]
    # return base  
user2390182
  • 72,016
  • 6
  • 67
  • 89
0

I suggest using

if base[index] < density:

instead of

while base[index] < density:
OnlyTrueJames
  • 47
  • 1
  • 8
0

hy randomobject123! I hope you are doing good. Kindly try this I hope this code will solve your problem.

Code

base = [
    {"name": "Mars", "Density": 5.427},
    {"name": "Earth", "Density": 5.513},
    {"name": "Venus", "Density": 5.204},
]
density = 5.500

def deletePlanet(density, base):
    return [i for i in base if i["Density"] >= density]
    
        

print(deletePlanet(density, base))

Results

[{'name': 'Earth', 'Density': 5.513}]
Sohaib Anwaar
  • 1,517
  • 1
  • 12
  • 29