I have a dictionary
dicte = [{'value':3, 'content':'some_string'}, {'value':4, 'content':'some_string1'}, {'value':4, 'content':'some_string2'}, {'value':4, 'content':'some_string3'}, {'value':4, 'content':'some_string4'}, {'value':5, 'content':'some_string5'}]
I want to be able to do an operation on that dictionary so that all the content that got the same values regarding the key "value" are regrouped and generate another dictionary based on that
The result here shuould be
new_dicte = [{'value':3, 'content':['some_string']}, {'value':4, 'content':['some_string1', 'some_string2', 'some_string3', 'some_string4']}, {'value':5, 'content':['some_string5']}]
What is the best pythonic way to do this ?
>Solution :
Here’s one way using dict.setdefault method to collect value–content pairs and unpacking later:
out = {}
for d in dicte:
out.setdefault(d['value'],[]).append(d['content'])
new_dicte = list(map(lambda x: dict(zip(('value','content'), x)), out.items()))
Here’s another method that doesn’t use an intermediate dictionary:
out = {}
for d in dicte:
if d['value'] not in out:
out[d['value']] = {'value':d['value'], 'content':[d['content']]}
else:
out[d['value']]['content'].append(d['content'])
new_dicte = list(out.values())
Output:
[{'value': 3, 'content': ['some_string']},
{'value': 4,
'content': ['some_string1', 'some_string2', 'some_string3', 'some_string4']},
{'value': 5, 'content': ['some_string5']}]