How can I remove a JSON element if there's already one with the same text?
Asked
Active
Viewed 59 times
1 Answers
1
I assume what you are trying to achieve is to remove JSON entries with duplicate values.
Note that in Python, a JSON element is the same as a dictionary. You can therefore just iterate through the dictionary and create a new dictionary which doesn't contain duplicates like so:
result = {}
for key,value in input_raw.items():
if value not in result.values():
result[key] = value
print(result)
Taken from Removing Duplicates From Dictionary. See that link for more information/alternate solutions.
For the input:
{
'key1':'a',
'key2':'b',
'key3':'b',
'key4':'c'
}
this successfully produces the ouptput:
{
'key1':'a',
'key2':'b',
'key4':'c'
}
-
-
@Idlehands what do you mean when they are nested? Could you give some example input. – Jan 03 '19 at 17:40
-
@Idlehands `{1:{1:'b'}, 2:{1:'b'}}` shall result in `{1:{1:'b'}}` with this code, but `{1:{1:'b'}, 2:{1:'c'}}` will result in an identical dictionary. That is the expected behaviour, if I am understanding the question right. – Jan 03 '19 at 17:46
-
What I'm saying is the question is unclear, your answer has certain assumptions that should be clarified by the question. If the `json` is `{1: 'b', 2: {3: 'b'}}` what happens then? These are clarifications required of the question. – r.ook Jan 03 '19 at 17:47
-
You're right. In my answer, I am assuming OP wants to remove duplicates of values that are equal to each other. Some clarification is needed. – Jan 03 '19 at 17:54