Search code examples
pythonmysqlsqlpymysql

How can I access data structured by labels in Python?


I'm doing some practice with python and mysql, using pymysql. After executing a query I get the result with the following structure:

{'Name': 'Company1', 'SALES': 1113.3, 'CURRENCY': 'USD'}

I want to use the 'SALES' value for operations, how can I have access to it?

My code so far is the following:

with connection.cursor() as cursor:
            # Revenue by Company (absolute)
            sql1 = "select `Company`.`Name`, `Company`.`SALES`, `Company`.`CURRENCY` from `Company` where `Company`.`Name` = 'Company1'"
            cursor.execute(sql1)
            result1 = cursor.fetchall()

Any ideas?

Thanks in advance!!


Solution

  • Since you are calling .fetchall, result1 is a list of dictionaries, with each element in this list being a row returned from the query. Therefore you will need to access the 'SALES' key in each dictionary (=row):

    for row in results1:
        print(row['SALES'])