Associating column names with query results
Imagine a database library that executes queries and only returns a list of tuples containing the values, which keeps the footprint small (the bigquery library does something like this). There's a little bit of hand waving here, but stick with me.
So we've got a list containing the table schema:
schema = ['id', 'first_name', 'last_name']
And the query results look like this:
query_results = [
(1, 'Thomas', 'Sowell',),
(2, 'Murray', 'Rothbard',),
(3, 'Friedrich', 'Hayek',),
(4, 'Adam', 'Smith',),
]
Depending on what we want to do with this data, we may want to turn this into a list of dictionaries, where the keys are the column names and the values are the corresponding query results.
Zip is our friend.
dict_results = [dict(zip(schema, row)) for row in query_results]
>> [{'id': 1, 'first_name': 'Thomas', 'last_name': 'Sowell'},
{'id': 2, 'first_name': 'Murray', 'last_name': 'Rothbard'},
{'id': 3, 'first_name': 'Friedrich', 'last_name': 'Hayek'},
{'id': 4, 'first_name': 'Adam', 'last_name': 'Smith'}]
Combining query string lists
Imagine we've got a front-end application that makes a GET request and passes a few lists in the query. And in our case, the elements of each list correspond to one another.
https://my-site.com/steps?title=step%20one&title=step%202&slug=step-one&slug=step-two
In our example request, there are two titles
and two slugs
in the query string. On the backend, we may want to associate them, and we can use zip to do this!
data = list(zip(request.GET.getlist('title'), request.GET.getlist('slug')))
>> [('step one', 'step-one'), {'step two', 'step-two')]