我有一个快速的。
我有一个很长的字典列表,看起来像这样:
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'}]
现在我想做一件简单的事情,我想从字典中删除这三个项目,'redcap_event_name','redcap_repeat_instrument','redcap_repeat_instance'。
我试着写这段代码,但它根本不删除
for k in mydict:
for j in k.keys():
if j == 'preliminary_arm_1':
del j
我的最终结果是原始的字典列表,但没有上面提到的3个项目。如有任何帮助,不胜感激
您可以遍历每个dict
,然后遍历您想要删除的每个键。最后从每个dict
中删除key
。
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)
输出:
[{'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'}]
也许有帮助:
[{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]