Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Json value extraction
#1
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()
Reply
#2
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"]))
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Request for Python code - Features extraction from JSON file (cuckoo) thinker 1 2,204 Apr-07-2021, 04:40 PM
Last Post: Larz60+
  eml file data extraction ajetrumpet 2 2,659 Jul-04-2020, 04:34 AM
Last Post: ajetrumpet
  Table extraction from scanned PDF RupamKundu 1 3,717 Aug-03-2019, 02:59 AM
Last Post: Larz60+
  Substring extraction nevendary 6 3,964 Apr-24-2019, 05:41 AM
Last Post: nevendary
  String extraction Scott 3 3,089 Jul-21-2018, 09:01 PM
Last Post: buran
  Automating a Data Extraction Process Harrison 12 8,676 Mar-31-2017, 10:44 AM
Last Post: Harrison

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020