Преобразование списка словарей
Имеется список словарей следующего вида:
a = [
{'animal': {'cats': {'шотландец': 1}}, 'id': 1},
{'animal': {'dogs': {'овчарка': 1}, 'fish': {'окунь': 1}, 'cats': {'сфинкс': 1}},'id': 2},
{'animal': {'birds': {'синица': 1}, 'fish': {'сельдь': 1}}, 'id': 3},
{'animal': {'dogs': {'овчарка': 1}, 'birds': {'воробей': 1}}, 'id': 4}
....]
Необходимо преобразовать его в следующий вид (учитывая, что брать нужно только ключи 'cats', 'dogs', 'birds':
[{"word": 'шотландец', 'count': 1, 'id': [1]},
{"word": 'овчарка', 'count': 2, 'id': [2, 4]},
{"word": 'сфинкс', 'count': 1, 'id': [2]},
{"word": 'синица', 'count': 1, 'id': [3]},
{"word": 'воробей', 'count': 1, 'id': [4]}]
Подскажите, как это можно сделать? Пыталась использовать следующий код, но не выдает нужный результат и не могу понять в чем проблема:
attribute = ['cats', 'dogs', 'birds']
animals = []
for i in range(0, len(a)):
for key in a[i]:
if key == 'animals':
for attr in attribute:
an = a[i][key].get(attr, {})
animals.append(an)
resw = []
for key, value in an.items():
result["entity"] = key
result["count"] = value
resw.append(result)
results = [x for x in named_entities if x]
Ответы (1 шт):
Автор решения: Zhihar
→ Ссылка
можно сделать так:
initial = [
{'animal': {'cats': {'шотландец': 1}}, 'id': 1},
{'animal': {'dogs': {'овчарка': 1}, 'fish': {'окунь': 1}, 'cats': {'сфинкс': 1}},'id': 2},
{'animal': {'birds': {'синица': 1}, 'fish': {'сельдь': 1}}, 'id': 3},
{'animal': {'dogs': {'овчарка': 1}, 'birds': {'воробей': 1}}, 'id': 4}
]
animals = dict()
for obj in initial:
for animal in obj['animal']:
if animal not in ('cats', 'dogs', 'birds'):
continue
name = list(obj['animal'][animal].keys())[0]
count = obj['animal'][animal][name]
if name not in animals:
animals[name] = {'word': name, 'count': 0, 'id': []}
animals[name]['count'] += count
animals[name]['id'] += [obj['id']]
res = list(animals.values())
print(res)
если предполагается, что внутри зверья много кличек (а то в примере только 1), то тогда так:
animals = dict()
for obj in initial:
for animal in obj['animal']:
if animal not in ('cats', 'dogs', 'birds'):
continue
for name, count in obj['animal'][animal].items():
if name not in animals:
animals[name] = {'word': name, 'count': 0, 'id': []}
animals[name]['count'] += count
animals[name]['id'] += [obj['id']]
res = list(animals.values())