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']
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.
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]))
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.