Populate a dictionary with the result of a query
问题 I'm currently doing this: cursor.execute('SELECT thing_id, thing_name FROM things') things = []; for row in cursor.fetchall(): things.append(dict([('thing_id',row[0]), ('thing_name',row[1]) ])) Is there some shorthand I can use to do this, or should I write a little helper function? 回答1: Using list comprehension: things = [{'thing_id': row[0], 'thing_name': row[1]} for row in cursor.fetchall()] or using list comprehension with zip: things = [dict(zip(['thing_id', 'thing_name'], row)) for row