0

My python2.7 code contains lambda sort technique to sort fetched elements according to the defined order. Yesterday i migrated from python 2.7 to python 3.6, The problem is after migration the line where i wrote lambda sort is throwing error in program. For migration from py2 to py3 i used lib2to3. I believe this is cause of some syntax miss match in py3, But couldn't figure it out. The error log is as mentioned below-

My code Fragment:


 property_sort_order = ['field', 'rename', 'selected', 'description']
        node_property_value_list = []
        node_property_value_list = node_property_value[nodekey]
        node_property_value_list = [OrderedDict(
             sorted(item.iteritems(), key=lambda (k, v): property_sort_order.index(k)))
                                for item in node_property_value_list]
                                    for item in node_property_value_list]
        #print node_property_value_list
        node_property_value[nodekey] = node_property_value_list

Errror:
        for item in node_property_value_list]
    TypeError: <lambda>() missing 1 required positional argument: 'v'
0

2 Answers 2

2

In Python 2 it is possible to unpack the (k, v) tuple in lambda/function arguments, but not in Python 3. You can either unpack the lambda inline,

lambda item: property_sort_order.index(item[0])

or unpack as a separate statement (which can't be done in a lambda).

def sort_key(item):
    k, v = item
    return property_sort_order.index(k)
sorted(..., key=sort_key)
Sign up to request clarification or add additional context in comments.

1 Comment

Its not helped @ephemient can u clarify this answer
1

You need to make key=lambda k, v: property_sort_order.index(k) into key=lambda k_v:property_sort_order.index(k_v[0]) - the lambda is getting passed a single tuple, which you can't destructure in python3.6.

4 Comments

Its not happening @Nathan Vērzemnieks
Sorry, not sure what you need. I wrote exactly what string to replace and how. What exactly is "not happening"? Do you get a different error?
sry mr @Nathan Vērzemnieks. i was wrong. your answer was helpful,tq
No problem! Glad it's sorted out.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.