Home > Back-end >  In python I'd like to eliminate some dictionary items ({n:[0,0]}) in a list of dictionaries
In python I'd like to eliminate some dictionary items ({n:[0,0]}) in a list of dictionaries

Time:12-11

d is the list of dictionaries, the items I want to remove from the list are: {3: [0, 0]},{5: [0, 0]}, {6: [0, 0]}, {7: [0, 0]}, {8: [0, 0]}.

Here's my failed attempt:

    d=[{1: [2.9, 1.04]}, {2: [1.45, 1.01]}, {3: [0, 0]}, {4: [9.5, 1.55]}, {5: [0, 0]}, {6: [0, 0]}, {7: [0, 0]}, {8: [0, 0]}]
    for i,v in enumerate(d):
        if v[i 1] == [0,0]: d.pop(i)
    File "<stdin>", line 2, in <module>
    KeyError: 3

Please help.

CodePudding user response:

Your data is a list of dictionaries. Iterating over a list and changing it is a bad idea. Use a list comprehension to filter out the undesirable items instead:

out = [i for i in d if list(i.values())[0] != [0,0]]   

Output:

[{1: [2.9, 1.04]}, {2: [1.45, 1.01]}, {4: [9.5, 1.55]}]

CodePudding user response:

for v in d[:]:
    if [0,0] in v.values():
        d.remove(v)
  • Related