Similar to Removing dicts with duplicate value from list of dicts, but seeking understanding not just an answer.
I am confronted with a result that exposes a fundamental gap in my understanding of lists, loops, or the list.remove()
function. Perhaps an explanation would be helpful to others facing the same question:
>>> my_dict_list = [
{'a': 50, 'b': 4000},
{'a': 4000, 'b': 4000},
{'a': 5000, 'b': 5000},
{'a': 501, 'b': 501},
{'a': 400, 'b': 100},
{'a': 4000, 'b': 4000},
{'a': 5000, 'b': 5000},
]
Resulting confusion using a simple loop to remove dicts where 'a' and 'b' values are equal:
>>> for d in my_dict_list:
... if d['a'] == d['b']:
... my_dict_list.remove(d)
...
>>> my_dict_list
[{'a': 50, 'b': 4000}, {'a': 5000, 'b': 5000}, {'a': 400, 'b': 100}, {'a': 5000, 'b': 5000}]
Not understanding the above is leaving a gaping wound in my soul. Some were removed, others were not.
BTW: this easily gets the correct result:
>>> [d for d in my_dict_list if d['a'] != d['b']]
[{'a': 50, 'b': 4000}, {'a': 400, 'b': 100}]