python - Deleting multiple items in a dict -
i've searched around error gives me, don't understand quite well. did for k, v in dbdata.items
, didn't work me neither, gives me other errors.
well, want delete multiple items.
tskinspath = ['1', '2'] # dbdata = {} dbdata['test'] = {} dbdata['test']['skins_t'] = {} # adds 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 # doesn't work 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
instead of iterating on dictionary, iterate on 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 = [] key, value in dbdata["test"]["skins_t"].iteritems(): if key not in tskinspath: if value == 0: to_be_deleted.append(key) k in to_be_deleted: del dbdata["test"]["skins_t"][k]
Comments
Post a Comment