Python Dict problems

James Henderson james at logicalprogression.net
Tue Feb 3 05:59:23 EST 2004


On Tuesday 03 February 2004 8:59 am, venu gopal wrote:
> Hello people,
> iam finding great difficulty in handling a two-dimentional dictionary or
> any other similar data structure for the following purpose:
> from a collection of words,i need to have the count of each word so if i
> use:
>                     str=f.getline()
>                     for l in range(flen):
>                           if subs[l].has_key(str):
>                                   subs[l][str]=1
>                           else:
>                                   subs[l][str]+=1
>
> for this iam getting an error as "Type error:cannot concatenate str + int"
> i would be very grateful to the python-list if any one of you could kindly
> help me in solving this problem.

It would help if you showed all your code.  Where are "f", "flen" and "subs" 
defined?  I don't understand why the problem you describe needs a nested (if 
that's what you mean by "two-dimensional") dictionary, but maybe I don't 
understand the problem you describe.

Here's a hint anyway that might help:

>>> words = ['asas', 'dsds', 'dsds', 'foo', 'bar']
>>> d = {}
>>> for word in words:
...     d[word] = d.get(word, 0) + 1
...
>>> d
{'dsds': 2, 'foo': 1, 'asas': 1, 'bar': 1}

By the way, "str" is not an ideal variable name since it masks a builtin type.

HTH
James
-- 
James Henderson, Logical Progression Ltd.
http://www.logicalprogression.net/
http://sourceforge.net/projects/mailmanager/





More information about the Python-list mailing list