我有一本字典,我想删除名字以s开头的键,即“person_3”。
My_Dict = {
"person_1": {"name": 'John', "age": 22, "Interests": ['football","cricket'],
"amount_deposited": [24000, 26000]},
"person_2": {"name": 'Nancy James', "age": 23, "Interests": ['baseball’,’cricket'],
"amount_deposited": [24000, 27000]},
"person_3": {"name": 'Selena Gomez', 'age': 26, "Interests": ['baseball', 'table tennis'],
"amount_deposited": [24000, 28000]}
}
2条答案
按热度按时间liwlm1x91#
尝试
del
```My_Dict = {
"person_1": {"name": 'John', "age": 22, "Interests": ['football","cricket'],
"amount_deposited": [24000, 26000]},
keys_to_be_deleted = []
first we need to get the keys which we need to delete
for each_person in My_Dict:
if(My_Dict[each_person]['name'].lower().startswith('s')):
keys_to_be_deleted.append(each_person)
now that we have the keys, we can delete them
for k in keys_to_be_deleted:
del My_Dict[k]
My_Dict
{'person_1': {'name': 'John',
'age': 22,
'Interests': ['football","cricket'],
'amount_deposited': [24000, 26000]},
'person_2': {'name': 'Nancy James',
'age': 23,
'Interests': ['baseball’,’cricket'],
'amount_deposited': [24000, 27000]}}
0ve6wy6x2#
在遍历旧词典时,对名称使用词典理解和测试。
要获取我的新命令,请执行以下操作: