[Tutor] put query result set into dictionary

Alan Gauld alan.gauld at btinternet.com
Thu Nov 11 02:03:30 CET 2010


"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/





More information about the Tutor mailing list