[Tutor] put query result set into dictionary

Shawn Matlock matlocs at odscompanies.com
Thu Nov 11 17:56:37 CET 2010


That was it. Thank you, Alan.

-----Original Message-----
From: tutor-bounces+matlocs=odscompanies.com at python.org [mailto:tutor-bounces+matlocs=odscompanies.com at python.org] On Behalf Of Alan Gauld
Sent: Wednesday, November 10, 2010 5:04 PM
To: tutor at python.org
Subject: Re: [Tutor] put query result set into dictionary


"Shawn Matlock" <matlocs at odscompanies.com> wrote

> I am trying to put the results of a MySQL query into a dictionary.
> It fails because it includes the Unicode delimiter - "u'somevalue'".

I don't think so...

> envsql = "select envVariable, envValue from ODS_ENV_DICT where 
> envName = 'ST2'"
> csdbCursor.execute(envsql)

> envDict = {}
> for envVariable, envValue in csdbCursor.fetchall():
>     envDict[envVariable].append(envValue)

Append is a list operation but you don;t have a list (yet).
You are just adding a single value to a dictionary.
You need something like:
      envDict[envVariable] = envValue

Or if you really want a list you need to check if the value is
there first and then append. You could do that with setdefault() like 
so:

      envDict.setdefault(envVariable, []).append(envValue)

Which returns the list if one exists or an empty list if it doesn't
and appends the value to it, it then assigns the resulting list
back to the dictionary at the key position

> Traceback (most recent call last):
>   File "H:\workspace\test\src\root\nested\example.py", line 33, in 
> <module>
>    envDict[envVariable].append(envValue)
> KeyError: u'envDB'

Despite the KeyError message its really because you are trying
to use append on a non existent list:

>>> d = {}
>>> d[5].append(7)
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
KeyError: 5

Same error, no unicode in sight.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/



_______________________________________________
Tutor maillist  -  Tutor at python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor




More information about the Tutor mailing list