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?
Using a plain
lambda
to iterate anything in Python sounds very wrong. Certainly the most Pythonic method to iterate sequences and collections is to use list comprehensions and generator expressions like @Andrey presented.If the interviewer was leaning on the more theoretical/Computer Sciencey answers, it is worth noting that using lambdas to iterate is quite possible, although I must stress that this is not Pythonic nor useful at any context other than academic exercises:
lambda
itself doesn't iterate anything. As you thought, it just defines an anonymous function - aside from the syntactic rule about only being able to have an expression, alambda
does nothing more than a similar function made usingdef
. The code inside the lambda might iterate something, but only in the same ways as any other function might use (provided they are expressions, and so valid inside alambda
).In the example you mention using
sorted
, the key function is called on each element of the list being sorted - but it issorted
itself that does this, and which does the iteration. When you provide a key function,sorted
does something broadly similar to this:As you can see,
sorted
does the iteration here, not thelambda
. Indeed, there is no reason why the key has to be a lambda - any function (or any callable) will do as far assorted
is concerned.At the lowest level, there is only really one way to iterate a dict (or, indeed, any other iterable) in Python, which is to use the iterator protocol. This is what the
for
loop does behind the scenes, and you could also use awhile
statement like this:The comments in this aren't strictly part of the iterator protocol, they are instead part of the
for
loop (but having at least a loop body in there is mostly the point of iterating in the first place).Other functions and syntax that consume iterables (such as list, set and dict comprehensions, generator expressions or builtins like
sum
,sorted
ormax
) all use this protocol, by either:for
loop,while
loop (especially for modules written in C),A class can be made so that its instances become iterable in either of two ways:
__iter__
(called byiter
), which returns an iterator. That iterator has a method called__next__
(justnext
in Python 2) which is called bynext
and returns the value at the iterator's current location and advances it (or raisesStopIteration
if it is already at the end); or__getitem__
in such a way that doingmy_sequence[0]
,my_sequence[1]
, up untilmy_sequence[n-1]
(wheren
is the number of items in the sequence), and higher indexes raise an error. You usually want to define__len__
as well, which is used when you dolen(my_sequence)
.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 untilStopIteration
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 functionmap(func, [1, 2, 3])
.The best way to iterate dict in python is:
But you can build it with lambda func:
You can iterate dict using lambda like this: