Home >Backend Development >Python Tutorial >How do I extract a list of unique dictionaries from a list of potentially duplicate 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.
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>
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>
After applying the solution:
<code class="python">print(unique_dicts) [{'id': 1, 'name': 'john', 'age': 34}, {'id': 2, 'name': 'hanna', 'age': 30}]</code>
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!