在python字典中按其值删除键

izkcnapc  于 2021-08-20  发布在  Java
关注(0)|答案(2)|浏览(305)

我有一本字典,我想删除名字以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]}
            }
liwlm1x9

liwlm1x91#

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

0ve6wy6x

0ve6wy6x2#

在遍历旧词典时,对名称使用词典理解和测试。

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

要获取我的新命令,请执行以下操作:

{'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]}}

相关问题