Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Merge a key values base on another key value

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 valuecontent 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']}]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading