0

I'm currently running into a problem with removing a key-value pair from a dictionary object in Python.

Say, a given multi-leveled dictionary is structured like this:

course = {
    'name': 'Python',
    'release_date': '2014-12-01',
    'author': {
        'name': 'john',
        'email': 'john@gmail.com'
    },
    'info': {
        'instructor': 'john',
        'price': 100,
        'location': {
            'city': 'beijing',
            'country': 'china'
        }
    }
}

I would like to remove the following keys from a list structured like so, with each underscore denoting a new level in the dictionary.

bad_keys = ['release_date', 'author_email', 'info_location_city']

Meaning, the resulting dictionary should be:

course = {
    'name': 'Python',
    'author': {
        'name': 'john',
    },
    'info': {
        'instructor': 'john',
        'price': 100,
        'location': {
            'country': 'china'
        }
    }
}

What is the most appropriate and / or optimal way of going about this? The key difference between this question and say other questions is the main idea of updating the current dictionary to have the reflected changes of the deleted key-value pairs. Being able to iteratively or recursively iterate through the dictionary isn't a problem, nor is collecting said data--The problem stems from being able to update the current dictionary either while iterating through it or after.

Shockercj
  • 3
  • 2
  • Please update your question with the code you have tried. – quamrana Aug 12 '22 at 21:48
  • Ok, I see your difficulty. You think that you have to iterate through the `course` dictionary. That's not the problem. You just have to iterate over the supplied keys. If you find an appropriate key you either need to delete that key, or access the sub `dict` and check for a different list of keys. – quamrana Aug 12 '22 at 22:09
  • Imagine that you had: `bad_keys = ['name']`. You shouldn't iterate over the keys to see if one of them is `'name'`, you iterate over `bad_keys` to see if one of those is in `course`. – quamrana Aug 12 '22 at 22:12
  • Cursed solution with exec: `(exec(f"""del course["{'"]["'.join(path.split())}"]""") for path in bad_keys)`. Note that this requires the keys in the chains to be separated by a space (i.e. `bad_keys = ['release_date', 'author email', 'info location city']`) instead of by an underscore (as this would conflict with keys that contain an underscore, e.g. `"release_date"`, which could be overcome by additional logic in this case, but not in general). – Michael Hodel Aug 12 '22 at 22:38

0 Answers0