python - 将重复的字典项目转换为具有 ID 数组的唯一项目

标签 python dictionary

我有一个字典列表,其中一个字典值 name 包含我想要规范化的重复数据。该列表如下所示:

[
    {'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。有时 document_ids 是相同的,但我只需要跟踪它们与名称的关联。所以上面的列表将变成:

[
     {'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]}
]

这是我迄今为止尝试过的代码:

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)

代码的主要问题是我正在比较并查找重复项,但是当我迭代到下一个项目时,它再次发现重复项,从而创建了某种无限循环。如何编辑代码,使其不会一遍又一遍地比较重复项?

最佳答案

new = dict()
for x in people:
    if x['name'] in new:
        new[x['name']].append({'document_id': x['document_id'], 'annotation_id': x['annotation_id']})
    else:
        new[x['name']] = [{'document_id': x['document_id'], 'annotation_id': x['annotation_id']}]

这不完全是您所要求的,但格式应该能够满足您的要求。

这是输出:

{'Craig McKray': [{'annotation_id': 8, 'document_id': 50}, {'annotation_id': 9, 'document_id': 50}], 'Western Union': [{'annotation_id': 11, 'document_id': 61}], 'None on file': [{'annotation_id': 5, 'document_id': 40}]}

在这里,我认为这可能更适合您:

from collections import defaultdict
new = defaultdict(dict)

for x in people:
    if x['name'] in new:
        new[x['name']]['document_ids'].append(x['document_id'])
        new[x['name']]['annotation_ids'].append(x['annotation_id'])
    else:
        new[x['name']]['document_ids'] = [x['document_id']]
        new[x['name']]['annotation_ids'] = [x['annotation_id']]

关于python - 将重复的字典项目转换为具有 ID 数组的唯一项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45157013/

相关文章:

python - 如何获取 types.SimpleNamespace 类型中的所有用户定义属性?

python - 在早上 7 点到下午 5 点从数据集中过滤掉 M-F 的更好方法?

python - 使用重复单元格值作为键将 pandas DataFrame 转换为字典

Haskell:对于 Map 中的每个 (k,v),用 k 和 v 执行 IO()

Python:list() 函数搞乱了 map()

python - 如何在机器人框架 HTTP 请求库中为 CreateSession 添加 header

python - 在 Google App Engine 上使用自定义域进行 Web2py 身份验证?

python - 计算边界框的面积

ios - 在 swift 2.0 中使用枚举字符串类型作为字典键

python - 我想将字典键从字符串更改为整数