lundi 4 octobre 2021

How to remove a dictionary from a list of dictionaries (using a given value)?

Essentially I was trying to remove a designated dictionary inside a list of dictionaries but unfortunately the loop I was coding only worked to delete the first dictionary and did not recognise the rest of the dictionaries within that same list. The code was similar to the one following:


list=[{"key1" : "value1", "key2" : "value2", "key3" : "value3"}, 
{"key1" : "value1", "key2" : "value2", "key3" : "value3"},
{"key1" : "value1", "key2" : "value2", "key3" : "value3"}]

def drop_dic():

    print("please insert value you want to remove")
    value3=input()
    
    for i in range(len(list)):
        
        if list[i]["key3"] == value3:
            
            key1_drop = vip_list[i]["key1"]
            key2_drop = vip_list[i]["key2"]
            
            del list[i]
            
            print ( key1_drop + " and " + key2_drop + " have been removed.")
            
            break
            
        else:
    
            print("This dict doe not exist")
        
            break

Basically if I try to remove the first dictionary from the list using the first key3 I am able to, but the rest of the dicts it just prints "this dict does not exist"

What should I change?

What is the best and simplest way to remove an identified dict from a list of dicts following a given value?

Aucun commentaire:

Enregistrer un commentaire