简体   繁体   中英

Removing nested keys in Python dictionary

I have a dictionary that looks like this:

data = {'a1': {'version': '1',
               'results': {'key':'value'}
              },
        'a2': {'version': '1', 
               'results': {'key':'value'}
              }
       }

I need to get rid of the key 'version' and have the output like this:

{'a1': {'results': {'key':'value'}},
 'a2': {'results': {'key':'value'}},
...

I got the code:

data2 = {}
for k, v in data:
    if k == 'version':
    data2[k] = None

However, this returns an empty dictionary.

What would be a proper code to achieve this?

data = {'a1': {'version': '1',
               'results': {'key':'value'}
              },
        'a2': {'version': '1', 
               'results': {'key':'value'}
              }
       }

for inner_dict_key in data:
    if 'version' in  data[inner_dict_key]:
        del data[inner_dict_key]['version']

Result:

{'a1': {'results': {'key': 'value'}}, 'a2': {'results': {'key': 'value'}}}

Python 3:

data2 = {k: {'results': v['results']} for k, v in data.items()}

Python 2:

replace items with iteritems

Explanation:

.items() gives us an iterator over (key, value) pairs

You can do this with a nested dict comprehension

data2 = {k: {k: v for k, v in v.items() if k != 'version'} for k, v in data.items()}

If you are confused by the scope of the k's and v's you can label the ones from the inner dict

data2 = {k: {k1: v1 for k1, v1 in v.items() if k1 != 'version'} for k, v in data.items()}

Making new dicts from comprehensions prevents accidental side-effects to dict as seen in the answers using del

This worked:

data2 = data.copy()
for k in data:
   if 'version' in data[k]:
       del data2[k]['version']
print(data2)

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