Home > Net >  Delete item from a list of Dictionaries
Delete item from a list of Dictionaries

Time:01-12

I have a quick one.

I do have a long list of dictionaries that looks like this:

mydict = [{'id': '450118',
  'redcap_event_name': 'preliminary_arm_1',
  'redcap_repeat_instrument': '',
  'redcap_repeat_instance': '',
  'date_today': '2022-11-04',
  'timestamp': '2022-11-04 10:49',
  'doc_source': '1',
  'hosp_id': '45',
  'study_id': '18',
  'participant_name': 'CHAR WA WAN',
  'ipno': '141223',
  'dob': '2020-06-30'},
{'id': '450118',
  'redcap_event_name': 'preliminary_arm_1',
  'redcap_repeat_instrument': '',
  'redcap_repeat_instance': '',
  'date_today': '2022-11-04',
  'timestamp': '2022-11-04 10:49',
  'doc_source': '1',
  'hosp_id': '45',
  'study_id': '01118',
  'participant_name': 'CHARIT',
  'ipno': '1413',
  'dob': '2020-06-30'}]

Now I want to do a simple thing, I do want to delete this 3 items from the dictionaries ,'redcap_event_name','redcap_repeat_instrument','redcap_repeat_instance'.

I have tried writing this code but its not deleting at all

for k in mydict:
    for j in k.keys():
        if j == 'preliminary_arm_1':
            del j

My final result is the original list of dictionaries but without the 3 items mentioned above. any help will highly be appreciated

CodePudding user response:

You can iterate over each dict and then iterate over each key you want to delete. At the end delete key from each dict.

del_keys = ['redcap_event_name','redcap_repeat_instrument','redcap_repeat_instance']

for dct in mydict:
    for k in del_keys:
        # To delete a key regardless of whether it is in the dictionary or not
        dct.pop(k, None)
print(mydict)

Output:

[{'id': '450118',
  'date_today': '2022-11-04',
  'timestamp': '2022-11-04 10:49',
  'doc_source': '1',
  'hosp_id': '45',
  'study_id': '18',
  'participant_name': 'CHAR WA WAN',
  'ipno': '141223',
  'dob': '2020-06-30'},
 {'id': '450118',
  'date_today': '2022-11-04',
  'timestamp': '2022-11-04 10:49',
  'doc_source': '1',
  'hosp_id': '45',
  'study_id': '01118',
  'participant_name': 'CHARIT',
  'ipno': '1413',
  'dob': '2020-06-30'}]

CodePudding user response:

Maybe it helps:

[{j: k[j] for j in k.keys() if j not in ['redcap_event_name','redcap_repeat_instrument','redcap_repeat_instance']} 
 for k in mydict]
  • Related