gpt-4-0314· OpenAI
WildChat-4.8M (AI2)
write me a Python code that Removes duplicate dicts in list
- User
write me a Python code that Removes duplicate dicts in list
- Assistant
You can use a combination of a for loop and a list comprehension to remove duplicate dictionaries from a list. Here's the code:
pythonlist_of_dicts = [ {"a": 1, "b": 2}, {"a": 2, "b": 2}, {"a": 1, "b": 3}, {"a": 1, "b": 2}, {"a": 2, "b": 2}, ] unique_dicts = [] for d in list_of_dicts: if d not in unique_dicts: unique_dicts.append(d) print(unique_dicts)This code will output:
python[ {"a": 1, "b": 2}, {"a": 2, "b": 2}, {"a": 1, "b": 3}, ]However, this solution doesn't work for dictionaries with unhashable values (e.g., lists or other dictionaries). In such cases, you can convert dictionaries to strings (e.g., using
json.dumps) or other hashable types before adding them to a set or checking their uniqueness.