vendredi 5 février 2016

Unique Database Records to JSON in Python

After request:

SELECT DISTINCT state, county, city FROM data

I have a sqlite database:

__________________________
|state|  county |   city |
|TX   | Harris  | Houston|
|TX   | Harris  | Baytown|
|TX   | Dallas  | Addison|
|CA   | Orange  | Irvine |
|CA   | Orange  | Tustin |
|NV   | Clark   |LasVegas|

And I'd like to get unique records as JSON like:

{
"TX" : {
    "Harris" : ["Houston", "Baytown"],
    "Dallas" : ["Addison"]
       },
"CA" : {
    "Orange" : ["Irvine", "Tustin"]
       },
"NV" : {
    "Clark" : ["LasVegas"]
       }
}

Right now I'm using this way:

c.execute("SELECT DISTINCT state FROM data")
states = c.fetchall()
filter = {}
for state in states:
    counties_select = "SELECT DISTINCT county FROM data WHERE state = '"+state+"' ORDER BY county ASC"
    c.execute(counties_select)
    counties = c.fetchall()
    filter[state] = {}
        for county in counties:
        city_select = "SELECT DISTINCT city FROM data WHERE county = '"+county+"' ORDER BY city ASC"
        c.execute(city_select)
        cities = c.fetchall()
        filter[state][county] = cities
 with open('filters.json', 'w') as outfile:
        json.dump(filter, outfile)
        outfile.close

What is the better way to do this in python 3.5 ?

Aucun commentaire:

Enregistrer un commentaire