I have a json file organised like the following one and I would like to delete all duplicated from 2 key pairs element
[{'name': 'anna', 'city': 'paris','code': '5'},
{'name': 'anna', 'city': 'paris','code': '2'},
{'name': 'henry', 'city': 'london','code': '1'},
{'name': 'henry', 'city': 'london','code': '3'},...]
expected outpout
[{'name': 'anna', 'city': 'paris'},{'name': 'henry', 'city': 'london'}]
I am struggling with this task, any ideas?
3
Answers
you need to make a unique key for (name, city) and for record whose have same pair just need to apply the condition of what to keep in the final result.
once done, get the values and that is the answer.
with
walrus
operator anddict-comprehension
In pure python you can select what you need in dictionnary rows, use set collection of hashable row like tuple (with {}) and then rebuild your rows with what you selected
Here’s another approach (one of many) that utilises a set as follows:
Output:
Note:
There’s at least one benefit of doing it this way. Other answers are building the new dictionaries to include keys ‘name’ and ‘city’ and implicitly ignore ‘code’ which is fine for the data as shown. However, this approach builds the new dictionaries excluding ‘code’. What this means is that the dictionary structures (the input data) can change without having to alter the functional code – i.e., the ‘code’ key could be absent and key/value pairs in addition to ‘name’ and ‘city’ could be introduced