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"
}
],
>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'}]