Python Practice › List Programs › Program 70
Remove duplicate dictionaries
Write a Python program to remove duplicate dictionaries from a list, keeping the first of each.
Input
[{"name": "john"}, {"city": "mumbai"}, {"Python": "language"}, {"name": "john"}]Output
[{'name': 'john'}, {'city': 'mumbai'}, {'Python': 'language'}]Approach
- Dicts are not hashable, so compare with the dicts already kept.
Solution
data = [{"name": "john"}, {"city": "mumbai"}, {"Python": "language"}, {"name": "john"}]result = []for d in data: if d not in result: result.append(d)print(result)Output
[{'name': 'john'}, {'city': 'mumbai'}, {'Python': 'language'}]Line by line
Line 4
in compares dicts by their contents.
Learn the concept
New to this topic? Read the lesson, then come back.