5

How should I got about rewriting this lambda to fit Python3 standards?

top10_popular = [k for (k, (v1, v2)) in sorted(site_freq_150users.items(),
                                           key=lambda (k, (v1, v2)): v2, reverse=True)[:10]

I've read that this has to do with the removal of tuple unpacking in Python3, but now I'm sure how to rewrite this correctly.

Thanks in advance.

1 Answer 1

3

Just make the argument list flat (i.e. 1-dimensional) by naming all the top-level arguments directly, without unpacking them. Do the unpacking later in the return expression.

In your example, you could do this by saying v = (v1, v2) and then creating the lambda like so:

lambda k, v : v[1]

UPDATE: Above does not work. Instead, you really have to put the whole item into the argument and then extract key and value from that:

lambda item : item[1][1]
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for the response. Unfortunately, this is not working. If site__freq_150users is a dictionary of the format {k : (v1, v2)}, I tried the following: for (k, (v1, v2)) in site_freq_150users.items(): v = (v1, v2) top10_popular = [k for (k, (v1, v2)) in sorted(site_freq_150users.items(), key=lambda k, v: v[1], reverse=True)][:10] , but got a "missing positional argument v" error. Seems like I am doing something very stupid and missing an obvious thing.
Thank you, I think that should work. I managed to do it by combining your approach, but eliminating the lambda altogether like so: v2_list = sorted([((v2, v1), k) for (k, (v1, v2)) in site_freq_150users.items()], reverse=True)[:10] and then extracting to a new list: top10 = [] for ((v2, v1), k) in v2_list: top10.append(k). Not very elegant, though, hahah.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.