python - 在 Python 字典中按其值删除键
问题描述
我有一本字典,我想在其中删除名称以 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]}
}
解决方案
尝试del
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]}
}
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]}}
推荐阅读
- php - 当数据库失败或我想永久断开数据库时,如何将用户重定向到 404 页面?
- java - Jackson ObjectMapper 不接受所有日期格式
- android-studio - 不要在真实硬件中构建和运行我的应用程序
- css - CSS - 导致溢出的网格
- php - 如果存在或不存在,如何对文件值进行 if 语句
- kubernetes - minikube 中的负载平衡
- mysql - sql计算多行课堂上的当前学生
- php - “CSRF 令牌无效。请尝试重新提交表单”在 Symfony3 中
- c# - First() & Single() 返回 1 个元素但需要所有元素
- visual-studio-code - 我们是否有任何用于 vscode 扩展的示例 ui 集成测试