根据条件从字典中删除key:value对?

时间:2019-03-25 19:31:52

标签: python python-3.x dictionary

我有嵌套的字典“ 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 个答案:

答案 0 :(得分:2)

首先,获取所有密钥,然后过滤要保留的密钥。然后,您可以仅保留以下键来重建新字典:

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}}