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

Merging list of dictionaries

I have the following list of dictionaries:

"entities": [
        {
            "length": 6,
            "offset": 0,
            "type": "bold"
        },
        {
            "length": 6,
            "offset": 0,
            "type": "italic"
        },
        {
            "length": 4,
            "offset": 7,
            "type": "italic"
        }
    ],

I would like to know how to use this input to derive the following list of dictionaries:

"entities": [
            {
                "length": 6,
                "offset": 0,
                "type": "bold_italic"
            },
            {
                "length": 4,
                "offset": 7,
                "type": "italic"
            }
        ],

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

>Solution :

Group each entry by their length and offset into a dictionary, noting the seen types in a list. Then, read off the computed result back into a list, creating a new dictionary for each unique length/offset pair and joining all of the types with underscores:

from collections import defaultdict

data = [
        {
            "length": 6,
            "offset": 0,
            "type": "bold"
        },
        {
            "length": 6,
            "offset": 0,
            "type": "italic"
        },
        {
            "length": 4,
            "offset": 7,
            "type": "italic"
        }
]

entry_types = defaultdict(list)
for item in data:
    key = item['length'], item['offset']
    entry_types[key].append(item['type'])

result = []
for (length, offset), types in entry_types.items():
    result.append(dict(length=length, offset=offset, type='_'.join(types)))

print(result)

This outputs:

[{'length': 6, 'offset': 0, 'type': 'bold_italic'}, {'length': 4, 'offset': 7, 'type': 'italic'}]
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