0

I was working on python2 for my project.Now I want to migrate from python2 to python3. I am getting syntax error while writing the for loop code snippet given below.I'm bit confused where I went wrong.

Code :

for k, val in sorted(datasource_columns.iteritems(), key=lambda(
                            k, v): sort_order.index(k)):
                        # columns.add_column(key, sorted(val))
                        columns.add_column(k, val)

where , sort_order = ['Name', 'Data Type', 'Type', 'Role']

2
  • 2
    Please include the actual error in your post. Commented Dec 11, 2017 at 9:12
  • 6
    sort_order.index(k) sounds like a very inefficient sort key... Commented Dec 11, 2017 at 9:15

3 Answers 3

1

As already said, iteritems() will be a problem, but you mention a syntax error, which comes from the lambda declaration with parenthesis:

Change:

key=lambda(k, v): sort_order.index(k)

To:

key=lambda k, v: sort_order.index(k)

But you may as well write this more efficient code:

for key in sort_order:
    val = datasource_columns.get(key)
    if val is not None: # to avoid getting None values in your columns
        columns.add_column(key, val)

In the future, please post the actual stacktrace whenever you get an exception, this makes it a lot easier to understand any issue.

Sign up to request clarification or add additional context in comments.

3 Comments

Your more efficient code has a slight problem: there may be keys in sort_order that aren't present in datasource_columns. Your code will create a (key, None) item for such keys. That may not be desirable.
Indeed, but that can be easily fixed with an if val is not None: statement, if required.
Certainly! So you should add that info to your answer. And it's probably worthwhile mentioning why the original key function is so horrible.
1
    key=lambda k, v: sort_order.index(k) 

does not work. TypeError: () missing 1 required positional argument: v

The needed change for Python 3 would be:


    test_list.sort(key = lambda args : sort_order.index(args[0])) 

Comments

0

Not sure what changed exactly but lambda (k, v): sort_order.index(k) is invalid syntax in python3. You can use lambda k, v: sort_order.index(k) instead.

Comments

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.