user2856692
user2856692

Reputation: 125

Error with Python dictionary: str object has no attribute append

I am writing code in python. My input line is "all/DT remaining/VBG all/NNS of/IN "

I want to create a dictionary with one key and multiple values For example - all:[DT,NNS]

groupPairsByKey={}
Code:
for line in fileIn:
    lineLength=len(line)
    words=line[0:lineLength-1].split(' ')
    for word in words:
        wordPair=word.split('/')
                  if wordPair[0] in groupPairsByKey:
                    groupPairsByKey[wordPair[0]].append(wordPair[1])
<getting error here>
                  else:
                    groupPairsByKey[wordPair[0]] = [wordPair[1]]

Upvotes: 1

Views: 20776

Answers (3)

aIKid
aIKid

Reputation: 28292

Your problem is that groupPairsByKey[wordPair[0]] is not a list, but a string!

Before appending value to groupPairsByKey['all'], you need to make the value a list.

Your solution is already correct, it works perfectly in my case. Try to make sure that groupPairsByKey is a completely empty dictionary.

By the way, this is what i tried:

>>> words = "all/DT remaining/VBG all/NNS of/IN".split
>>> for word in words:
    wordPair = word.split('/')
    if wordPair[0] in groupPairsByKey:
        groupPairsByKey[wordPair[0]].append(wordPair[1])
    else:
        groupPairsByKey[wordPair[0]] = [wordPair[1]]


>>> groupPairsByKey
{'of': ['IN'], 'remaining': ['VBG'], 'all': ['DT', 'NNS']}
>>> 

Also, if your code is formatted like the one you posted here, you'll get an indentationError.

Hope this helps!

Upvotes: 4

unutbu
unutbu

Reputation: 879739

Although it looks to me like you should be getting an IndentationError, if you are getting the message

str object has no attribute append

then it means

groupPairsByKey[wordPair[0]]

is a str, and strs do not have an append method.


The code you posted does not show how

groupPairsByKey[wordPair[0]]

could have a str value. Perhaps put

if wordPair[0] in groupPairsByKey:
    if isinstance(groupPairsByKey[wordPair[0]], basestring):
        print('{}: {}'.format(*wordPair))
        raise Hell

into your code to help track down the culprit.


You could also simplify your code by using a collections.defaultdict:

import collections
groupPairsByKey = collections.defaultdict(list)
for line in fileIn:
    lineLength=len(line)
    words=line[0:lineLength-1].split(' ')
    for word in words:
        wordPair=word.split('/')
        groupPairsByKey[wordPair[0]].append(wordPair[1])

When you access a defaultdict with a missing key, the factory function -- in this case list -- is called and the returned value is used as the associated value in the defaultdict. Thus, a new key-value pair is automatically inserted into the defaultdict whenever it encounters a missing key. Since the default value is always a list, you won't run into the error str object has no attribute append anymore -- unless you have code which reassigns an old key-value pair to have a new value which is a str.

Upvotes: 2

scorpiodawg
scorpiodawg

Reputation: 5752

You can do:

my_dict["all"] = my_string.split('/')

in Python,

Upvotes: 1

Related Questions