Print all records as a dictionary in Python
It is not very convenient to output records from the database as a tuple, since it is not visible to which fields the received values belong. To solve this problem, you need to set the flag dictionary=True
in the cursor
method parameter.
Let's rewrite our code to print all records from the users
table as a dictionary:
query = "SELECT * FROM users"
with connection.cursor(dictionary=True) as cursor:
cursor.execute(query)
result = cursor.fetchall()
for row in result:
print(row)
The console will display a convenient dictionary, in which the keys will be the names of the fields, and the values will be the entries in the fields:
{'id': 1, 'name': 'user1', 'age': 23, 'salary': 400}
{'id': 2, 'name': 'user2', 'age': 25, 'salary': 500}
{'id': 3, 'name': 'user3', 'age': 23, 'salary': 500}
{'id': 4, 'name': 'user4', 'age': 30, 'salary': 900}
{'id': 5, 'name': 'user5', 'age': 27, 'salary': 500}
{'id': 6, 'name': 'user6', 'age': 28, 'salary': 900}
Output all data from the users
table as a dictionary.