I have an interview recently. The interviewer asked me the ways to iterate dict in python
. I said all the ways use for statement. But he told me that how about lambda?
I feel confused very much and I consider lambda as an anonymity function, but how it iterates a dict? some code like this:
new_dict = sorted(old_dict.items(), lambda x: x[1]) # sorted by value in dict
But in this code, the lambda is used as a function to provide the compared key. What do you think this question?
Iterating Through .items()The view object returned by .items() yields the key-value pairs one at a time and allows you to iterate through a dictionary in Python, but in such a way that you get access to the keys and values at the same time.
A lambda function is a small anonymous function. A lambda function can take any number of arguments, but can only have one expression.
Since a for loop is a statement (as is print , in Python 2. x), you cannot include it in a lambda expression. Instead, you need to use the write method on sys. stdout along with the join method.
In Python, the lambda function is an anonymous function. This one expression is evaluated and returned. Thus, We can use lambda functions as a function object. In this article, we will learn how to iterate with lambda in python.
You don't iterate with lambda
. There are following ways to iterate an iterable object in Python:
for
statement (your answer)[x for x in y]
, dictionary {key: value for key, value in x}
and set {x for x in y}
(x for x in y)
map
, all
, itertools
module) next
function until StopIteration
happens.Note: 3 will not iterate it unless you iterate over that generator later. In case of 4 it depends on function.
For iterating specific collections like dict or list there can be more techniques like while col: remove element
or with index slicing tricks.
Now lambda
comes into the picture. You can use lambdas in some of those functions, for example: map(lambda x: x*2, [1, 2, 3])
. But lambda here has nothing to do with iteration process itself, you can pass a regular function map(func, [1, 2, 3])
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With