Home > Backend Development > Python Tutorial > How do I extract a list of unique dictionaries from a list of potentially duplicate dictionaries?

How do I extract a list of unique dictionaries from a list of potentially duplicate dictionaries?

Mary-Kate Olsen
Release: 2024-10-26 08:53:03
Original
787 people have browsed it

How do I extract a list of unique dictionaries from a list of potentially duplicate dictionaries?

How to Get a List of Unique Dictionaries

Given a list of dictionaries, obtaining a list of unique dictionaries can be useful for various purposes. The challenge lies in removing duplicate dictionaries while preserving the content.

Solution

One efficient approach involves creating a temporary dictionary where the key is the unique identifier from each dictionary. This effectively filters out any duplicates. The values of this temporary dictionary can then be retrieved as a list of unique dictionaries.

<code class="python"># In Python 3
unique_dicts = list({v['id']:v for v in L}.values())

# In Python 2.7
unique_dicts = {v['id']:v for v in L}.values()</code>
Copy after login

Example

Consider the list of dictionaries:

<code class="python">L = [
    {'id': 1, 'name': 'john', 'age': 34},
    {'id': 1, 'name': 'john', 'age': 34},
    {'id': 2, 'name': 'hanna', 'age': 30},
]</code>
Copy after login

After applying the solution:

<code class="python">print(unique_dicts)
[{'id': 1, 'name': 'john', 'age': 34}, {'id': 2, 'name': 'hanna', 'age': 30}]</code>
Copy after login

Key Insight

The key insight is that dictionaries can be converted into unique representations by using a common identifier as the key. This allows for efficient filtering of duplicates while preserving the original dictionary content.

The above is the detailed content of How do I extract a list of unique dictionaries from a list of potentially duplicate dictionaries?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template