简体   繁体   中英

how to remove values from a dictionary

I'm just starting to code and I don't understand why this code doesn't work and how to make it work

asd = {
"a":"b",
"d":"c",
"e":"f",
"g":"h",
}
for x in asd:
   if x == "f":
       del asd[x]
print(asd)

That's because you need to delete an element by key ("e"), not by value ("f").

asd = {
"a":"b",
"d":"c",
"e":"f",
"g":"h",
}

del asd["e"]
print(asd)

Your full code should look like this:

asd = {
"a":"b",
"d":"c",
"e":"f",
"g":"h",
}

# You need to copy the keys of the dictionary with `list(asd)`, 
# because you can't edit the dictionary while iterating it.
for key in list(asd):
    if asd[key] == "f":
        del asd[key]

print(asd)

One other approach is to use copy as following:

import copy

asd = {
"a":"b",
"d":"c",
"e":"f",
"g":"h",
}

asd_copy = copy.copy(asd)

for k,v in asd_copy.items():
    if v == "f":
        del asd[k]

print(asd)

The output is:

{'a': 'b', 'd': 'c', 'g': 'h'}

Without copy or list, you keep receive the following error:

RuntimeError: dictionary changed size during iteration

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM