Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lambda in python can iterate dict?

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?

like image 976
chyoo CHENG Avatar asked Oct 12 '15 09:10

chyoo CHENG


People also ask

Can dictionaries be iterated in Python?

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.

What is lambda in Python dictionary?

A lambda function is a small anonymous function. A lambda function can take any number of arguments, but can only have one expression.

Can lambda have for loop?

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.

Is lambda iterator in Python?

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.


1 Answers

You don't iterate with lambda. There are following ways to iterate an iterable object in Python:

  1. for statement (your answer)
  2. Comprehension, including list [x for x in y], dictionary {key: value for key, value in x} and set {x for x in y}
  3. Generator expression: (x for x in y)
  4. Pass to function that will iterate it (map, all, itertools module)
  5. Manually call 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]).

like image 193
Andrey Avatar answered Sep 26 '22 20:09

Andrey