How to retrieve data as a dictionary instead of a tuple using MySQL's fetchall() method

I have a table with the columns id, col1, col2, and col3. When I ran the query, this is how it was executed:

cur.execute(query)
row = cur.fetchall()

Is there a way to store the data in the variable row inside a dictionary so that I can pass this result to an API?

The output of cur.fetchall() looks like this:

((id, col1, col2, col3), (id, col1, col2, col3), (id, col1, col2, col3))

Can I format the result as follows?

[
   { id: value, col1: value, col2: value, col3: value },
   { id: value, col1: value, col2: value, col3: value },
   { id: value, col1: value, col2: value, col3: value }
]

I understand that I can iterate through the fetchall() results and extract values using a dictionary concept, such as:

rows = cursor.fetchall()
for row in rows:
    id = row['id']
    col1 = row['col1']
    # and so on...

Can I convert rows into a dictionary before passing it?

Answer №1

When utilizing the mysql-connector library for database connectivity, a quick method is to enable the dictionary option to True within the cursor function:

db = connector.connect(**config)

cursor = db.cursor(dictionary=True)

Answer №2

To efficiently merge the output values with cursor.description, you should use the "zip" function:

The columns are extracted using list comprehension: [col[0] for col in cursor.description]
Rows are then populated by zipping the columns with each row fetched: [dict(zip(columns, row)) for row in cursor.fetchall()]

Answer №3

To simplify the process, consider utilizing the DictCursor:

import MySQLdb
...
cursor = db.cursor(MySQLdb.cursors.DictCursor)

If desired, you can apply this setting to all cursors generated by db by including the cursor_class parameter in the connect function.

For more information on cursor variations, refer to:

Answer №4

I made a few changes to alecxe's solution by zipping each row within the cursor loop. This approach could be useful if you are dealing with a large table and want to avoid storing all rows in memory.

cursor = db.execute_sql("select * from something")
columns = [col[0] for col in cursor.description]
for row in cursor.fetchall():
    row = dict(zip(columns, row))
    print(row)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Incorporating XML Tree Structure from One File into Another Using Python and LXML

I have a specialized XML document containing tree structures, elements, attributes, and text. My goal is to utilize this XML as a template for generating another XML document that may differ in the number of elements compared to the original (e.g., the tem ...

Having trouble accessing a URL using Selenium in Python, but the browser opens without any issues

from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.keys import Keys import time import datetime ch_options = webdriver.ChromeOptions() ch_options.add_argument("--user-data-dir=C:\ ...

Converting synchronous Python methods into asynchronous tasks

Have you heard of the Task.Run method in C# that accepts a delegate as a parameter and returns a task that can be awaited? Check it out here. Now, I'm wondering if there is a similar feature in Python's asyncio module. I have a synchronous bloc ...

What is the correct way to iterate through a NumPy array containing tuples?

Having a Numpy 2D matrix filled with zeros and a list of coordinates in Numpy, my goal is to update the matrix using the given coordinates by passing them into a function. This is what I attempted : import numpy as np def update(coords): return np_ar ...

When using BeautifulSoup, there may be instances where the table element is not always detected, resulting in a 'NoneType' error being returned on occasion

Hello everyone, I am trying to retrieve accurate daily temperatures from www.wunderground.com and encountering the 'NoneType' error occasionally. For instance, the code below attempts to fetch the temperature data from March 1 to March 5, 2020. S ...

I encountered an error which reads UnboundLocalError: the local variable 'current' was referenced before being assigned

def initiate_countdown(number): while (count > 0): print(count) count -= 1 print("Liftoff!") initiate_countdown(5) ...

Having trouble dealing with certificate OS pop-ups in Selenium using Python? I attempted to use pyAutoGUI, but unfortunately, it was not successful

Working with Selenium in Python to navigate on Google Chrome has been a smooth process until an SSL certificate popup appeared. Despite having a valid certificate and simply needing to press 'Ok', it seems that this particular popup is not browse ...

What is the best way to initiate a new selenium session for each login attempt?

My goal is to automate a website using Python and Selenium. I have created functions for logging in and opening the Selenium browser. app = Flask(__name__) app.logger.addHandler(logging.StreamHandler(sys.stdout)) app.logger.setLevel(logging.ERROR) @app.r ...

Add Python 2.7.8 (64-bit) to your system without overwriting the current Python27 installation

Is it possible to install Python 2.7.8 (64-bit) on Windows 7 without having to replace the existing Python27 (64-bit) installation? ...

Ways to organically sort a string containing various numbers

Can someone help me with human sorting on the list below? I need to sort it based on the last numbers, for example, 45-50, 35-40, etc. list_list= ['N1-1TWS-AD03-____-001N-__45-50', 'N1-1TWS-AD01-____-001N-__50-54', 'N1-1 ...

Issues with data accuracy in HTML forms and implementing PHP pagination

I recently followed a tutorial on PHP pagination, titled Pagination - A Comprehensive Guide, to showcase data from a MySQL database. However, I encountered an issue where only the latest form submission was being displayed on the page, and I'm seeking ...

Can Python be used to control browsing?

Looking to control my web browser with Python, I want to be able to input commands in the terminal that will affect the browser - such as opening it, searching for specific content, scrolling through pages, and closing the window. So far, I have successfu ...

Tips on saving extracted information into separate lists

Below is the code snippet I am working with: lokk = [] nums = 7 for _ in range(nums): inner = driver.find_element_by_xpath( "/html/body/div[1]/div[2]/div/div/div/div[2]/div/div/div/div[2]/div[2]/div/div/div[2]/div[5]/span[1]").get_at ...

having difficulty in transforming a json to a dataframe

I'm currently facing an issue with converting a large JSON file into a data frame for sentiment analysis preprocessing. Despite my efforts, I am unable to successfully complete the conversion. The error seems to be related to pd.read_json method. im ...

Efficiently verifying whether a Python string can be easily converted to a float or integer

I am looking for the most efficient way to convert all strings in a large array to int or float types, if possible. Many people recommend using try-except or regex approaches, like the one discussed in Checking if a string can be converted to float in Pyth ...

Guidelines for running multiple lines of code in Python using Selenium

Currently, I am in the process of creating a stock trading bot to experiment with buying and selling on a stock trading simulator. After completing all the necessary web scraping and send_keys tasks, I find myself wanting to streamline the code execution w ...

What is the process for using Python to choose multiple blocks from various files at once?

I am looking to extract multiple blocks (parts) from a file and similar files. The sample file provided below is downloaded from the internet. The sections marked with 'session_start' and 'session_end' indicate the blocks/parts I want ...

What is the best way to obtain a list of dictionaries that is distinct?

In the dictionary, each key is unique. However, when appending dictionaries into a list, each dictionary is separated with its own values which may include duplicated keys. Each key within the separate dictionary in the list. For my current project, I am ...

choose checkbox option in python

Suppose you have an XML document structured as follows: <!-- Location --> <w:t>Location:</w:t> <w:t>Home:</w:t> <w:t>Extension:</w:t> <w:t>Hajvali –Prishtina</w:t> <w:t>Street. "Martyrs of Goll ...

Generating combinations of numbers from sets of indexes

If I have a numpy array and want to create tuples of triplets, quadruplets, or quintuplets from pairs of indices meeting certain criteria, how can I accomplish this? For instance, if we consider the example provided where pairs_tuples is [(1, 0), (3, 0), ...