What's the one liner for the below code?
for k,v in d2.items():
if d1.get(k,0) < v:
return False
return True
I tried this but it's invalid syntax.
return False if d1.get(k,0)<v for k,v in d2.items() else True
Why?
What's the one liner for the below code?
for k,v in d2.items():
if d1.get(k,0) < v:
return False
return True
I tried this but it's invalid syntax.
return False if d1.get(k,0)<v for k,v in d2.items() else True
Why?
return not any(d1.get(k, 0) < v for k, v in d2.items())
or
return all(d1.get(k, 0) >= v for k, v in d2.items())
return False if any([d1.get(k,0)<v for k,v in d2.items()]) else True
return False if [True for k, v in d2.items() if d1.get(k, 0) < v] else True
return not [True for k, v in d2.items() if d1.get(k, 0) < v]
Your code is not syntactically correct because the return
statement needs one or more expressions.
So, the for
statement is not an expression and that's why it fails.
In the code above I wrote a list comprehension, which is an expression, because at the end it is a list.
Then, I make an if
to the list (which in fact checks the length of the list, and if it is empty it will be a 0, which is considered False, while any other number is considered True).
The second code, which does not have the if
statement, has the not
operator, which does the check described earlier with the if
and then returns a boolean.
I hope this explains why that happened, which was your second question.
And also, this post is responding to your main question and not asking why you want it to be one liner. I would prefer to use the multiline version you posted, so you don't store any values and break instantly.
I would prefer to use the multiline version you posted, so you don't store any values and break instantly.
Reading wjandrea correct solution, I correct myself, with any
you don't have to store any value, it returns True
immediately after it finds a True
value, so it is as efficient as the multiline version.