简体   繁体   中英

Remove key:value pair from dictionary based on a condition?

I have nested dictionary 'my_dict' as given below. I want to remove common keys from nested dictionary grouped by main key name format.

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

For example, common keys in nested dictionary for keys starting abc* is 00000000. So, I want to remove this key. Likewise, i want to do for all. Expected result is given below:

Expected Result:

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

First, get all the keys, then filter which keys you wish to keep. Then you can reconstruct the new dict with only the keys to keep:

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

result:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM