【问题标题】:combine nested dictionaries in list of nested dictionaries based on matching key:value pair基于匹配键:值对在嵌套字典列表中组合嵌套字典
【发布时间】:2021-10-20 02:32:33
【问题描述】:

我尝试用谷歌搜索并找到一个与我的用例非常相似的问题:combine dictionaries in list of dictionaries based on matching key:value pair。但它似乎与我的情况没有 100% 对应,因为我有嵌套字典列表。假设我有一个嵌套字典列表(超过 2 个),但在这种情况下,我考虑使用两个嵌套字典来作为示例:

my_list = [{'sentence': ['x',
   'ray',
   'diffractometry',
   'has',
   'been',
   'largely',
   'used',
   'thanks',
   'to',
   ],
  'mentions': [{'mention': [27, 28],
    'positives': [26278, 27735, 21063],
    'negatives': [],
    'entity': 27735}]},
 {'sentence': ['x',
   'ray',
   'diffractometry',
   'has',
   'been',
   'largely',
   'used',
   'thanks',
   'to',
   ],
  'mentions': [{'mention': [13, 14],
    'positives': [7654],
    'negatives': [],
    'entity': 7654}]}]

如何根据键(句子)和值(所有标记的列表)的匹配来合并这两个字典,以便我可以得到如下期望的结果:

my_new_list = [
{'sentence': ['x',
   'ray',
   'diffractometry',
   'has',
   'been',
   'largely',
   'used',
   'thanks',
   'to',
   ],
  'mentions': [
    {'mention': [27, 28],
    'positives': [26278, 27735, 21063],
    'negatives': [],
    'entity': 27735
    },
   {'mention': [13, 14],
    'positives': [7654],
    'negatives': [],
    'entity': 7654
     }
   ]
}
]

在匹配键(句子):值(所有标记的列表)时如何合并键“提及”列表?在我的实际列表中,会有很多相同风格的词典。

非常感谢您的帮助。

【问题讨论】:

  • 你应该让你的例子更小。这将对您和我们都有帮助:)
  • @log0-- 感谢您的建议。我从关键“句子”中减少了一些标记。

标签: python dictionary merge


【解决方案1】:
my_dict = {}
for row in my_list:
    key = ' '.join(row['sentence']) # use sentence as key
    if key in my_dict:
        my_dict[key]['mentions'].extend(row['mentions'])
    else:
        my_dict[key] = row
        
my_list = list(my_dict.values())

【讨论】:

    【解决方案2】:

    据我了解,您希望按“句子”对信息进行分组。

    你可以通过迭代你的数组并填充一个由句子索引的列表字典来做到这一点。

    类似:

    from collections import defaultdict
    sentences = defaultdict(list)
    for element in my_list:
       key = tuple(element["sentence"])
       sentences[key].append(element)
    

    这给了你

     { sentence1: [element1, element2], sentence2: [element3] }
    

    从那里应该可以轻松构建你想要的结构。

    edit删除了对特定字段的引用

    【讨论】:

    • 你能用代码设计一个解决方案吗?当我尝试使用链接时,我搜索但我无法解决问题。
    • 将句子转换为元组以使其可散列(可用作字典中的键)
    • 当您有两个以上的列表时,该解决方案不起作用。
    • @Erwinwin 你是什么意思?你能写下结构吗
    • 我的意思是当您在该列表中有两个以上嵌套字典时,此解决方案不起作用。
    猜你喜欢
    • 2021-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-09
    • 1970-01-01
    • 1970-01-01
    • 2011-05-13
    相关资源
    最近更新 更多