I Have a sorted data as follows. I want to compare them and remove anything duplicated. Here I do an simple comparison of field to test the code. Original requirement is to some complex comparison. So I need compare the previous with the successor explicitly.
The comparison is not that simple. This is just to show what I am going to achieve. There are several field that need to compare (but NOT all) and remove the previous if same values and keep the newer one which will be having a incremental number. Hence explicit comparison is required. What is the problem in pop() and append() even I don't iterate it?
I used both list and deque. But duplicates are there. Anything wrong with code?
import collections
data = [
{'name': 'Atomic', 'age': 28},
{'name': 'Atomic', 'age': 28},
{'name': 'Atomic', 'age': 28},
{'name': 'Atomic', 'age': 29},
]
dq = collections.deque()
for i in range(1, len(data)):
prev_name = data[i-1]['name']
prev_age = data[i-1]['age']
next_name = data[i]['name']
next_age = data[i]['age']
dq.append(data[i-1])
if prev_name == next_name and prev_age == next_age:
dq.pop()
dq.append(data[i])
else:
dq.append(data[i])
print(dq)
Output (actual): deque([{'name': 'Atomic', 'age': 28}, {'name': 'Atomic', 'age': 28}, {'name': 'Atomic', 'age': 28}, {'name': 'Atomic', 'age': 29}])
Output (expected): deque([{'name': 'Atomic', 'age': 28}, {'name': 'Atomic', 'age': 29}])