i want to remove the itemes that them value is lower than18 in this dict but ithas eror:dictionary changed size during iteration | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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)

1st Jul 2020, 9:26 PM
mahsa
mahsa - avatar
7 Answers
+ 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)
1st Jul 2020, 9:42 PM
Jayakrishna 🇮🇳
+ 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/
1st Jul 2020, 10:49 PM
ChaoticDawg
ChaoticDawg - avatar
2nd Jul 2020, 10:03 AM
Ipang
0
Jayakrishna🇮🇳 thanks ,but my question wants me to delet some items from the first dict..what can i do?
1st Jul 2020, 9:46 PM
mahsa
mahsa - avatar
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...
1st Jul 2020, 9:50 PM
Jayakrishna 🇮🇳
0
1st Jul 2020, 9:55 PM
mahsa
mahsa - avatar
0
mahsa you're welcome..
1st Jul 2020, 9:56 PM
Jayakrishna 🇮🇳