Search code examples
pythondictionarydel

Deleting multiple items in a dict


I've searched around for the error it gives me, but I don't understand that quite well. They did something with for k, v in dbdata.items, but that didn't work for me neither, it gives me other errors.

Well, I want is to delete multiple items.

tskinspath = ['1', '2']   

#
dbdata = {}
dbdata['test'] = {}
dbdata['test']['skins_t'] = {}

# Adds the items
dbdata['test']['skins_t']['1'] = 1
dbdata['test']['skins_t']['2'] = 0
dbdata['test']['skins_t']['3'] = 0
dbdata['test']['skins_t']['4'] = 0

# This doesn't work
for item in dbdata["test"]["skins_t"]:

     if item not in tskinspath:

        if dbdata["test"]["skins_t"][item] == 0:

                    del dbdata["test"]["skins_t"][item]

# exceptions.RunetimeError: dictonary changed size during iteration

Solution

  • Instead of iterating over the dictionary, iterate over dict.items():

    for key, value in dbdata["test"]["skins_t"].items():
         if key not in tskinspath:
            if value == 0:
                del dbdata["test"]["skins_t"][key]
    

    On py3.x use list(dbdata["test"]["skins_t"].items()).

    Alternative:

    to_be_deleted = []
    for key, value in dbdata["test"]["skins_t"].iteritems():
         if key not in tskinspath:
            if value == 0:
                to_be_deleted.append(key)
    for k in to_be_deleted: 
        del dbdata["test"]["skins_t"][k]