【问题标题】:Delete Key by its value in Python Dictionary在 Python 字典中按其值删除键
【发布时间】:2021-09-20 13:16:37
【问题描述】:

我有一个字典,我想在其中删除名称以 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]}
            }

【问题讨论】:

    标签: python dictionary functional-programming


    【解决方案1】:

    在遍历旧字典时使用字典理解并测试名称。

    my_new_dict = {person: subdict for person, subdict in My_Dict.items() if My_Dict[person]['name'][0].lower() != 's'}
    

    获得这个 my_new_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]}}
    

    【讨论】:

    • 也许有助于解释听写理解
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2020-03-15
      • 2016-03-28
      • 1970-01-01
      • 2012-03-18
      • 2014-09-02
      • 2013-04-08
      • 2019-05-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多