我嵌套了字典“my_dict”,如下所示。我想从按主键名称格式分组的嵌套字典中删除公共键。my_dict = {'abc_1': {'00000000': 0.01555745891946835, 'facility': 0.04667237675840505, 'among': 0.01555745891946835}, 'abc_2': {'00000000': 0.01555745891946835, 'before': 0.04667237675840505, 'last': 0.01555745891946835}, 'mno_1': {'hello': 0.01555745891946835, 'hola': 0.04667237675840505, '0000150000': 0.01555745891946835}, 'mno_2': {'hello': 0.01555745891946835, 'name': 0.04667237675840505, '0000150000': 0.01555745891946835}, 'oko_1': {'err': 0.01555745891946835, 'error': 0.04667237675840505, '7812': 0.01555745891946835}, 'oko_2': {'9872': 0.01555745891946835, 'error': 0.04667237675840505, '00': 0.01555745891946835}}例如,嵌套字典中以 abc* 开头的键的常用键是 00000000。所以,我想删除这个键。同样,我想为所有人做。预期结果如下:预期结果:result_dict = {'abc_1': {'facility': 0.04667237675840505, 'among': 0.01555745891946835}, 'abc_2': {'before': 0.04667237675840505, 'last': 0.01555745891946835}, 'mno_1': {'hola': 0.04667237675840505}, 'mno_2': {'name': 0.04667237675840505}, 'oko_1': {'err': 0.01555745891946835, '7812': 0.01555745891946835}, 'oko_2': {'9872': 0.01555745891946835, '00': 0.01555745891946835}}
1 回答
梦里花落0921
TA贡献1772条经验 获得超6个赞
首先,获取所有密钥,然后筛选您希望保留的密钥。然后,您可以仅使用要保留的键来重建新的 dict:
all_keys = [n for k in my_dict.values() for n in k.keys()]
keys_to_keep = {k for k in all_keys if all_keys.count(k) == 1}
result_dict = {k: {kk: v[kk] for kk in keys_to_keep if kk in v} for k, v in my_dict.items()}
结果:
{'abc_1': {'facility': 0.04667237675840505, 'among': 0.01555745891946835}, 'abc_2': {'before': 0.04667237675840505, 'last': 0.01555745891946835}, 'mno_1': {'hola': 0.04667237675840505}, 'mno_2': {'name': 0.04667237675840505}, 'oko_1': {'err': 0.01555745891946835, '7812': 0.01555745891946835}, 'oko_2': {'9872': 0.01555745891946835, '00': 0.01555745891946835}}
添加回答
举报
0/150
提交
取消