辞書の値がname
のいずれかで正規化するデータのリストがあります。リストは次のようになります。辞書の項目を重複してIDの配列を持つユニークなアイテムに変換する
[
{'name': 'Craig McKray', 'document_id': 50, 'annotation_id': 8},
{'name': 'None on file', 'document_id': 40, 'annotation_id': 5},
{'name': 'Craig McKray', 'document_id': 50, 'annotation_id': 9},
{'name': 'Western Union', 'document_id': 61, 'annotation_id': 11}
]
私がしたいのは、一意の名前だけを含む新しい辞書を作成することです。しかし、私はdocument_idsとannotation_idsを追跡する必要があります。ドキュメントIDは同じであることもありますが、名前に関連付けられたものだけをトラッキングする必要があります。ときに私
result = []
# resolve duplicate names
result_row = defaultdict(list)
for item in data:
for double in data:
if item['name'] == double['name']:
result_row['name'] = item['name']
result_row['record_ids'].append(item['document_id'])
result_row['annotation_ids'].append(item['annotation_id'])
result.append(result_row)
コードの主な問題は、私が比較して重複を見つけるのですが、以下は
[
{'name': 'Craig McKray', 'document_ids': [50], 'annotation_ids': [8, 9]},
{'name': 'None on file', 'document_ids': [40], 'annotation_id': [5]},
{'name': 'Western Union', 'document_ids': [61], 'annotation_ids': [11]}
]
は、私がこれまで試してみましたコードです:だから上記のリストはに変わるだろう次のアイテムに反復すると、重複したループが再度生成され、無限ループが生成されます。重複を何度も何度も比較しないようにコードを編集するにはどうすればよいですか?
あなたが取得している出力を投稿してください。 – perigon