How to use Loop for Removing duplicate dictionaries in a list In Python
The basic method that comes to our mind while performing this operation is the naive method of iterating the list of dictionaries in Python and manually removing the duplicate dictionary and appending to the new list.
# using naive method
# initializing list
test_list = [{"Akash" : 1}, {"Kil" : 2}, {"Akshat" : 3},
{"Kil" : 2}, {"Akshat" : 3}]
# printing original list
print ("Original list : " + str(test_list))
# using naive method to
# remove duplicates
res_list = []
for i in range(len(test_list)):
if test_list[i] not in test_list[i + 1:]:
res_list.append(test_list[i])
# printing resultant list
print ("Resultant list is : " + str(res_list))
Output:
Original list : [{'Akash': 1}, {'Kil': 2}, {'Akshat': 3}, {'Kil': 2}, {'Akshat': 3}]
Resultant list is : [{'Akash': 1}, {'Kil': 2}, {'Akshat': 3}]
Python | Removing duplicate dicts in list
Removal of duplicates is essential in many applications. A list of dictionaries is quite common and sometimes we require to duplicate the duplicated. Let’s discuss certain ways in which we can remove duplicate dictionaries in a list in Python.
Contact Us