简体   繁体   中英

Delete a key of a list of dicts within a list of dicts

I have a list of dicts within a list of dicts and I would like to delete the key options that is part of the list of dictionaries in questions . I haven't been able to find a solution so far, what would be the best way to do this?

[{'id': 1,
  'type': 'FIXED',
  'questions': [
   {'id': 79401,
    'options': {'labels': {'left': 'No',
      'right': 'Yes'}}}],
{'id': 2,
 'type': 'MULTI',
 'questions': [
   {'id': 79402,
    'options': {'randomize': 'none',
    'captionText': '...'}}]}]

Iterate over the nested lists with a nested for loop, and then you can del the key you want to delete:

>>> data = [{'id': 1,
...   'type': 'FIXED',
...   'questions': [
...    {'id': 79401,
...     'options': {'labels': {'left': 'No',
...       'right': 'Yes'}}}]},
... {'id': 2,
...  'type': 'MULTI',
...  'questions': [
...    {'id': 79402,
...     'options': {'randomize': 'none',
...     'captionText': '...'}}]}]
>>> from pprint import pprint
>>> for d in data:
...     for q in d['questions']:
...         del q['options']
...
>>> pprint(data)
[{'id': 1, 'questions': [{'id': 79401}], 'type': 'FIXED'},
 {'id': 2, 'questions': [{'id': 79402}], 'type': 'MULTI'}]

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