0
i want to remove the itemes that them value is lower than18 in this dict but ithas eror:dictionary changed size during iteration
how can i fix it a={"math":15,"geography":20,"history":13,"basketball":19} for i in a: if a[i]<18: del a[i] print(a)
7 Respostas
+ 1
Use iterable Dict as a copy like... a.copy().
Edit:
a={"math":15,"geography":20,"history":13,"basketball":19}
for i in a.copy():
if a[i]<18:
del a[i]
print(a)
+ 2
Sounds like you could use the filter function.
a = dict(filter(lambda item: item[1] > 17, a.items()))
https://docs.python.org/3/library/functions.html#filter
https://thispointer.com/python-filter-a-dictionary-by-conditions-on-keys-or-values/
+ 1
Maybe this works
https://code.sololearn.com/c551r0jOW0c6/?ref=app
0
Jayakrishnađźđł thanks ,but my question wants me to delet some items from the first dict..what can i do?
0
mahsa it deletes from original dictionary only...
According to your code, Just before start of loop, it will have a copy as iterable, which is not changing in loop, but you deleting from original...
0
Jayakrishnađźđł thank a lot
0
mahsa you're welcome..