Lambda in python can iterate a dict?

I have an interview recently. The interviewer asked me about how to iterate a dict in python . I said that all ways to use for . But he told me what about lambda ?

I am very confused and I think lambda is a function of anonymity, but how does it iterate? some code:

 new_dict = sorted(old_dict.items(), lambda x: x[1]) # sorted by value in dict 

But in this code, lambda is used as a function to provide the compared key. What do you think this question is?

+6
source share
5 answers

You are not iterating with lambda . The following ways to repeat an iterative object in Python are:

  • for (your answer)
  • Understanding, including a list of [x for x in y] , a dictionary {key: value for key, value in x} and set {x for x in y}
  • Generator expression: (x for x in y)
  • Go to the function that will itertools over it ( map , all , itertools ).
  • Manually call the next function until StopIteration .

Note: 3 will not repeat it unless you go through this generator later. In case 4, it depends on the function.

To repeat certain collections, such as a dict or list, there may be more methods such as while col: remove element or using tricks to determine the index.

Now lambda appears in the picture. You can use lambdas in some of these functions, for example: map(lambda x: x*2, [1, 2, 3]) . But lambda has nothing to do with the iteration process here, you can pass the regular map(func, [1, 2, 3]) function map(func, [1, 2, 3]) .

+5
source

You can iterate a dict using lambda as follows:

 d = {'a': 1, 'b': 2} values = map(lambda key: d[key], d.keys()) 
+2
source

Using simple lambda to repeat something in Python sounds very wrong. Of course, the most Pythonic method for iterating over sequences and collections is to use list concepts and generator expressions like @Andrey.

If the interviewer relied on more theoretical answers / Computer Sciencey, it is worth noting that using lambda for iteration is quite possible, although I must emphasize that this is not Pythonic and is not useful in any context other than academic exercises:

 # the legendary Y combinator makes it possible # to let nameless functions recurse using an indirection Y = lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args))) # our iterator lambda it = lambda f: lambda Lst: (Lst[0], f(Lst[1:])) if Lst else None # see it in action: Y(it)([1,2,3]) => (1, (2, (3, None))) 
+1
source

Best way to iterate a dict in python:

 dic ={} iter_dic = dic.iteritems().next iter_dic() ... iter_dic() 

But you can create it using the lambda function:

 iter_dic = lambda dic: dic.keys()[0],dic.pop(dic.keys()[0]) iter_dic(dic) ... iter_dic(dic) 
0
source

lambda itself does not iterate over anything. As you thought, it simply defines an anonymous function - in addition to the syntax rule just for the possibility of having an expression, lambda does nothing more than a similar function created with def . The code inside the lambda can repeat something, but only in the same way as any other function (if they are expressions and therefore valid inside lambda ).

In the example that you mention with sorted , the key function is called for each element of the sorted list, but it itself sorted does it and does an iteration. When you provide a key function, sorted does something like this:

 def sorted(seq, key): decorated = [(key(elem), i) for i, elem in enumerate(seq)] # Sort using the normal tuple lexicographic comparisons decorated.sort() return [seq[i] for _,i in decorated] 

As you can see, sorted here, not lambda . Indeed, there is no reason why the key should be lambda - any function (or any called) will do before sorted .


At the lowest level, there is only one way to iterate through a dict (or indeed any other iterable) in Python that needs to use the iterator protocol. This is what the for loop runs behind the scenes, and you can also use the while statement as follows:

 it = iter(my_iterable) while True: try: val = next(it) except StopIteration: # Run else clause of for loop break else: # Run for loop body 

The comments in this are not strictly part of the iterator protocol, they are part of the for loop (but having at least the body of the loop, this is basically the iteration point in the first place).

Other functions and syntax that consume iterations (such as list, set, and dictations, generator expressions, or inline expressions such as sum , sorted or max ) use this protocol either:

  • Using the Python for loop,
  • Running something like the above while (especially for modules written in C),
  • Delegating to another function or piece of syntax that uses one of these

A class can be made so that its instances become iterable in one of two ways:

  • Provide an iterator protocol directly. You need a method called __iter__ (called by iter ) that returns an iterator. This iterator has a method called __next__ (just next in Python 2), which is called next and returns the value at the current location of the iterator and advances it (or raises StopIteration if it is already at the end); or
  • Implement a portion of the sequence protocol (which means that you behave like a list or tuple). For forward iteration, it is sufficient to define __getitem__ so that my_sequence[0] , my_sequence[1] , up to my_sequence[n-1] (where n is the number of elements in the sequence), and higher indices increase the error. Usually you also want to define __len__ , which is used when you do len(my_sequence) .
0
source

All Articles