Python Practice › List Programs › Program 70

Remove duplicate dictionaries

EasyList Programs · 70 of 100

Write a Python program to remove duplicate dictionaries from a list, keeping the first of each.

Advertisement
Input
[{"name": "john"}, {"city": "mumbai"}, {"Python": "language"}, {"name": "john"}]
Output
[{'name': 'john'}, {'city': 'mumbai'}, {'Python': 'language'}]

Approach

  1. Dicts are not hashable, so compare with the dicts already kept.

Solution

Python
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.

More list programs

← All 100 List Programs

Leave a Comment