Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

delete values in dictionary in python

Why this code is not going to the second "if part" but when I comment out the remove statements then it is going to the second "if part" i need to take out 'abc' and 'abcd' and 'defg' from d['a'] below is my code.

d={'a': ['abc','def','ghi','abcd','ghij'], 'b': [6, 7, 8]}
for i in d['a']:
    if i.startswith("a"):
        d['a'].remove(i)
        #print('1st print '+i)
    if i.startswith("d"):
        d['a'].remove(i)
        #print('2nd print '+i)
print(d)
like image 344
devender Avatar asked Mar 31 '26 16:03

devender


1 Answers

It is not a good practice to remove element from a list while iterating over it. In your case you can use a simple list comprehension.

Ex:

d={'a': ['abc','def','ghi','abcd','ghij'], 'b': [6, 7, 8]}
d["a"] = [i for i in d["a"] if not i.startswith(("a", "d"))]

print(d)

Output:

{'a': ['ghi', 'ghij'], 'b': [6, 7, 8]}
like image 150
Rakesh Avatar answered Apr 02 '26 11:04

Rakesh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!