简体   繁体   中英

Removing key from all level of a dictionary in Python

I have a list of dicts. Each dict can be nested. I want to remove the key id from each one of the dics, recursively. Fopr example (Note that I don't know if the amount of levels):

"files" : [ 
    {
      'id': 'ada21321',
      'd': 'asdasdas',
      'data': {
          'd': 'asdasdas'
      }
    },
    {
      'id': 'ada23112341321',
      'd': 'asdasdas',
      'data': {
          'd': 'asdasdas',
          'id': 'asdasd21asda'
      }
    }
],

I don't know how nested the dics are, and where id is located. I need to remove id from all of the dics from all levels. Output:

"files" : [ 
    {
      'd': 'asdasdas',
      'data': {
          'd': 'asdasdas'
      }
    },
    {
      'd': 'asdasdas',
      'data': {
          'd': 'asdasdas'
      }
    }
],

I know how to remove in one level:

for current_file in data["files"]:
    current_file.pop('id', None)

Is there an elegant way to achieve it?

This should do it for you:

def remove_key(container, key):
    if type(container) is dict:
        if key in container:
            del container[key]
        for v in container.values():
            remove_key(v, key)
    if type(container) is list:
        for v in container:
            remove_key(v, key)

remove_key(data['files'], 'id')

Output:

{'files': [{'d': 'asdasdas', 'data': {'d': 'asdasdas'}}, {'d': 'asdasdas', 'data': {'d': 'asdasdas'}}]}

You can use recursion:

data = {'files': [{'id': 'ada21321', 'd': 'asdasdas', 'data': {'d': 'asdasdas'}}, {'id': 'ada23112341321', 'd': 'asdasdas', 'data': {'d': 'asdasdas', 'id': 'asdasd21asda'}}]}
def d_rem(d):
   if not isinstance(d, dict):
      return d if not isinstance(d, list) else list(map(d_rem, d))
   return {a:d_rem(b) for a, b in d.items() if a != 'id'}

new_d = d_rem(data) 

Output:

{'files': [{'d': 'asdasdas', 'data': {'d': 'asdasdas'}}, {'d': 'asdasdas', 'data': {'d': 'asdasdas'}}]}

This should do the trick (note that this will remove any id keys regardless of whether the associated value to that id key is a str or dict ):

def remove_id(file):

    for k in list(file.keys()):
        if isinstance(file[k], dict):
            remove_id(file[k])
        if k=='id':
            del file[k]

for file in files:
    remove_id(file)

Yields:

[{'d': 'asdasdas', 'data': {'d': 'asdasdas'}}, {'d': 'asdasdas', 'data': {'d': 'asdasdas'}}]

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