Simple problem, I have it solved .. but python has a million ways to solve the same problem. I don’t want the most terse solution, I just want one that makes more sense than the following:
# sql query happens above, returns multiple rows
rows = cursor.fetchall()
cursor.close()
cntdict = {}
for row in rows:
a, b, c = row[0], row[1], row[2]
cntdict = {
a : { "b":b, "c":c }
}
print dict(cntdict)
note, a is always unique above. I want a dictionary created from the result set. Later on in my script I need to reference the values in the dictionary for each row that occurred. I’m trying to index the dictionary by making the key the value from the var a. that should point to another dictionary with two more key/value pairs that describe a… unless there’s a smarter/shorter way to do it.
You can do the same thing with a generator expression and the dictionary constructor:
And here is the code in action:
I can’t remember if MySQLdb returns rows as list of tuples, if that is the case then you can do this: