Frage

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
War es hilfreich?

Lösung

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]

Andere Tipps

The error message says it: you shouldn't modify the dictionary that you are iterating over. Try

for item in set(dbdata['test']['skins_t']):
   ...

This way you are iterating over a set that contains all keys from dbdata['test']['skins_t'].

As the question details is way aside from the question, If you are looking for a solution that deletes multiple keys from a given dict use this snippet

[s.pop(k) for k in list(s.keys()) if k not in keep]

Additionally, you can create a new dict via comprehension.

new_dict = { k: old_dict[k] for k in keep }
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top