user3389779
user3389779

Reputation: 15

Appending multiple values to a key in a dictionary

lst is a list of strings.

I keep getting an error say append does not work for the string type. It makes sense that word_dict[len(word)] is a string, but I am not sure how else to append multiple values to the same key.

for word in lst:
    if len(word) == int(wordLength):
        if len(word) in word_dict:
            word_dict[len(word)] = word_dict[len(word)].append(word)
        else:
            word_dict[len(word)] = word

print word_dict

Upvotes: 0

Views: 161

Answers (3)

Mauregg
Mauregg

Reputation: 1

Only problem you have here is that you set the value to be a string, namely 'word'. The error is because you cannot append an element in a string, so the only thing you have to do is to make sure you set the value to be a list. You can append an element to a list.

for word in lst:

if len(word) == int(wordLength):

   if len(word) in word_dict:

       word_dict[len(word)] = word_dict[len(word)].append(word)

   else:

       word_dict[len(word)] = [word]

print word_dict

Upvotes: 0

User
User

Reputation: 24731

There is no append function for the String class, and that's why you have an here.

See the String functions here: http://docs.python.org/2/library/string.html

To append strings, use +

string1 = "hi my name is: "
string2 = "ryan miller"
print string1 + string2

Append is used when merging lists.

So instead of:

word_dict[len(word)] = word_dict[len(word)].append(word)

Use:

word_dict[len(word)] = word_dict[len(word)] + word

Upvotes: 0

user2357112
user2357112

Reputation: 280485

Make the value a list of words. collections.defaultdict(list) can do that automatically:

word_dict = collections.defaultdict(list)

...

# Whether the key has anything associated with it or not
word_dict[whatever].append(word)

Upvotes: 1

Related Questions