I have a list of dictionaries with all of them having the same keys such as
input = [
{
"animal": "Tiger"
"country": "US",
"color": "yellow-black"
},
{
"animal": "Dog"
"country": "UK",
"color": "brown"
},
{
"animal": "Tiger"
"country": "Nepal",
"color": "yellow-black"
}
]
I would like to create a new dictionary where the ones which share the same value for a specified key (here animal) are grouped together. While grouping them I would like to remove the 'animal' key from the initial dictionaries. For the given example it would like this
output = {
"Tiger":
[{
"country": "US",
"color": "yellow-black"
},
{
"animal": "Tiger"
"country": "Nepal",
"color": "yellow-black"
}],
"Dog": [
{
"country": "UK",
"color": "brown"
}]
}
I achieve this with the code below, but I am quite sure that there must be a more elegant approach to this. Is it possible to write this as a one-liner?
grouped = dict((k, list(g)) for k, g in itertools.groupby(input, key=lambda x:x['animal']))
for k, g in grouped.items():
for i in range(len(grouped)):
del g[i]['animal']
"animal": "Tiger"in the output? As in, it's a repeated item that you've categorised under the primary keygroupbyapproach, the "Tiger" list only has the nepalese tiger; the US tiger is not present. For this reason I don't think thegroupbyapproach is a practical one.