首页 > 解决方案 > 在 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]}
            }

标签: pythondictionaryfunctional-programming

解决方案


尝试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]}}

推荐阅读