Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code optimization python loops [closed]

My code looks like this:

if query.orderby:
    for q in query.orderby:
        if 'severity' in q:

Note: query.orderby is a list of dict. Looks something like [{"severity": "asc"},{"name": "desc"}] How can i optimize these lines? Is there any way to replace the for loop and still get same functionality as the code above?

like image 867
NSP Avatar asked Aug 17 '26 09:08

NSP


2 Answers

Something like this:

filtered = [q for q in query.orderby if 'severity' in q]

would filter into a new list

like image 76
Zitrax Avatar answered Aug 19 '26 15:08

Zitrax


If query.orderby is a list of dict than you should go like that:

x = [{"severity": "asc"}, {"name": "desc"}]

for e in x:
    for key, value in e.iteritems():
        if 'severity' in key:
            print 'yes'
like image 40
Rajiv Sharma Avatar answered Aug 19 '26 15:08

Rajiv Sharma



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!