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?
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])
.