I have a JSON object where there are duplicate keys. I want to merge all the values as a string under one key using a ";" separator
input:
{
"1061": "GROCERY",
"1073": "GM-HBC",
"4220": "PRODUCE",
"958": "MEAT",
"958": "DAIRY",
"958": "FROZEN"
}
desired output:
{
"1061": "GROCERY",
"1073": "GM-HBC",
"4220": "PRODUCE",
"958": "MEAT;DAIRY;FROZEN"
}
I copied the question and data from this (link) since this is exactly what I’m looking for, except I want to do this in python.
3
Answers
Here’s a solution using
itertools.groupby
andjson.loads(..., object_pairs_hook=...)
:You can use the multidict library to create a MultiDict, which is like a regular dictionary but can hold multiple values for the same key.
Here is a similar solution to @BoppreH, but does not use
itertools
.Output:
Notes
The
setdefault()
method will create the key/value if the key does not exist in the dictionary. If the key already exists, it does not do anything. Further more, thesetdefault()
method returns the value corresponding to the key. Thus the codeis a shorthand for