Python Forum

Full Version: Json value extraction
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have the fallowing code.

for (ID, Info) in mycursor:
print("ID {}, Population {}".format(ID, Info))


It is returning a table with values like this:
ID 4079, Population {"Population": 92020}

I want it to return:
ID 4079, Population 92020

I am stuck trying to parse this. Not sure how to tackle this. I am new to Python.
Thanks to everyone who read this.

Not sure if this is decent but this is what I came up with on my own.

import json
import mysql.connector

mydb = mysql.connector.connect(
    host="localhost",
    user="####",
    passwd="####",
    database="world_x")


mycursor = mydb.cursor()

selectIdInfoSQL = "SELECT ID, Info from world_x.city"

mycursor.execute(selectIdInfoSQL)

for (ID, Info) in mycursor:
    pop = Info
    pop = pop[15:len(pop)-1]
    print("ID {}, Population {}".format(ID, pop))
    UpdateSQL = "UPDATE world_x.city set Population = %s WHERE ID = %s"
    value = (pop, ID)
   
    mydb2 = mysql.connector.connect(
            host="localhost",
            user="####",
            passwd="####",
            database="world_x")
    mycursor2 = mydb2.cursor()
    mycursor2.execute(UpdateSQL, value)
    mydb2.commit()
    print(mycursor2.rowcount, "record(s) affected")

mycursor.close()
mydb.close()
Generally speaking, you should simplify your code before asking a question about it. In this case, SQL is not related to this question, so everything about it can be removed. Really your question comes down to this:

Simplified-question asker Wrote:I'm struggling with printing a dictionary in a specific way. Here's my code:
data = {"Population": 92020}
print(data)
Actual result: {"Population": 92020}
Desired result: Population 92020

Now to actually answer your question... if you know that the Population key is always going to present, and it's the only thing you care about, you can do this
data = {"Population": 92020}
print("Population {Population}".format(**data))
or perhaps more directly
data = {"Population": 92020}
print("Population {}".format(data["Population"]))