Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python : Remove the key if its value is lower than 2

Tags:

python

There is a list containing 2 dictionaries, if I want to delete the key of 'zxc' that contains a value lower than 2, what should I do in the next step?

aa = [{'asd': 'qwe', 'zxc': 5}, {'zxc': 1, 'rty': 'uio'}]

def try_test():
    if 'zxc' < 2:
        del aa['zxc']

but it doesn't work.

like image 434
DragonCentre Avatar asked Aug 06 '26 09:08

DragonCentre


1 Answers

The problem in your code is that aa is a list of dictionaries so aa['zxc'] is not clear.

Instead you should loop through each index in the list and compare as follows:

aa = [{'asd': 'qwe', 'zxc': 5}, {'zxc': 1, 'rty': 'uio'}]

def try_test():
    for ind in aa:
        if ind['zxc'] < 2:
            del ind['zxc']

    print(aa)

try_test()

Output:

[{'zxc': 5, 'asd': 'qwe'}, {'rty': 'uio'}]
like image 105
lbragile Avatar answered Aug 08 '26 00:08

lbragile



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!