I have following list of dictionaries:
d = [
{ 'name': 'test', 'regions': [{'country': 'UK'}] },
{ 'name': 'test', 'regions': [{'country': 'US'}, {'country': 'DE'}] },
{ 'name': 'test 1', 'regions': [{'country': 'UK'}], 'clients': ['1', '2', '5'] },
{ 'name': 'test', 'regions': [{'country': 'UK'}] },
]
What is the easiest way to remove entries from the list that are duplicates ?
I saw solutions that work, but only if an item doesn't have nested dicts or lists
You can remove duplicates from a Python using the dict. fromkeys(), which generates a dictionary that removes any duplicate values. You can also convert a list to a set. You must convert the dictionary or set back into a list to see a list whose duplicates have been removed.
To remove a dictionary from a list of dictionaries: Use a list comprehension to iterate over the list. Exclude the matching dictionary from the new list. The list comprehension will return a new list that doesn't contain the specified dictionary.
Dictionary. Dictionaries are used to store data values in key:value pairs. A dictionary is a collection which is ordered*, changeable and do not allow duplicates.
The straight answer is NO. You can not have duplicate keys in a dictionary in Python. But we can have a similar effect as keeping duplicate keys in dictionary.
How about this:
new_d = []
for x in d:
if x not in new_d:
new_d.append(x)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With