user5495269
user5495269

Reputation: 147

python copy to multiple variables

I iterate results from SQL

for row in results:
    name = row[0]
    email = row[1]
    lastlogon = row[2]
    # do somthing with the parameters

The row has more than three elements. Is there a way to do that in a single line:

for row in results:
    name, email, lastlogon = row
    # do somthing with the parameters

?

Upvotes: 0

Views: 534

Answers (1)

Nicolas Heimann
Nicolas Heimann

Reputation: 2581

If you want your row with a "readable" mapping, you could map the results using a mapping list and the function zip. The mapping specifies how the n-th entry in row is labeled.

mapping = ['name', 'email', 'lastlogon', 'more_fields', 'again_more_fields', 'and_so_on']
for row in results:
   readable_row = dict(zip(mapping, row))
   print(readable_row)
   # will print something like {'name': '...', 'email': '...', ...}

That way you can map as many items as you want to a dict and use it

if row['and_so_on'] == 'peter pan':
   do_some_funny_stuff()

As a guess, I would bet that the SQL framework you are using also provides some methods to return the resulting rows as dicts with their corresponding field names as keys. Which framework are you using?

Also if you want your values in variables, you can slice the row. This allows you to only assign the first n values.

name, email, lastlogon = row[0:3]

Upvotes: 1

Related Questions