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)
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)

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