1
name_list = [{'name': 'John'}, {'name': 'Johan'}, {'name': 'John'}]

    for i in xrange(len(name_list)):
        if name_list[i]["name"] == "John":
            del name_list[i]

After the first time recognizing John, it deletes that object but breaks out of the function. How can I continue traversing till the end and delete every single JSON object which has John as name?

Many thanks guys!

Jim Clermonts
  • 1,694
  • 8
  • 39
  • 94

2 Answers2

6

You shouldn't remove items form a sequence you are currently iterating over. It's much safer to build a new dictionary without the elements you don't want:

new_list = [d for d in name_list if d['name'] != 'John']
kylieCatt
  • 10,672
  • 5
  • 43
  • 51
0

This will give you what you are looking for. Trick is to delete from the end of the list first (highest index).

name_list = [{'name': 'John'}, {'name': 'Johan'}, {'name': 'John'}]

for index, i in enumerate(reversed(name_list)):
    if i['name'] == 'John':
        del name_list[index]
Red Shift
  • 1,312
  • 2
  • 17
  • 29