Question

Python 3 How do I add multiple non-integer values to a key in a dictionary? Here's...

Python 3

How do I add multiple non-integer values to a key in a dictionary?

Here's the code that this question came from. It's part of a larger program. text_string is a string and ngram_length is a user-defined integer. I tried using an if/else statement to initialize the dictionary with the first value and then to add subsequent values to the key but append doesn't work :(

def build_dictionary(text_string, ngram_length):
    dictionary = {}
    first = 0
    last = ngram_length
    while first < len(text_string) - ngram_length:
        if text_string[first:last] not in dictionary:
            dictionary[text_string[first:last]] = text_string[last]
        else:
            dictionary[text_string[first:last]].append(text_string[last])               #ERROR#
        first += ngram_length
        last += ngram_length
    print(dictionary)
0 0
Add a comment Improve this question Transcribed image text
Answer #1
def build_dictionary(text_string, ngram_length):
    dictionary = {}
    first = 0
    last = ngram_length
    while first < len(text_string) - ngram_length:
        if text_string[first:last] not in dictionary:
            dictionary[text_string[first:last]] = [text_string[last]]
        else:
            dictionary[text_string[first:last]].append(text_string[last])    
        first += ngram_length
        last += ngram_length
    print(dictionary)


Add a comment
Know the answer?
Add Answer to:
Python 3 How do I add multiple non-integer values to a key in a dictionary? Here's...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT