I have this small function that is not doing what I want it to do, and I am not sure why. The function is supposed to add the new_text
string to the text
list in the wordclouds
dictionary.
def update(wordclouds, source, new_text):
if source in wordclouds:
old_text = wordclouds[source]['text']
frank = old_text.append(new_text)
wordclouds[source]['text'] = frank
else:
wordclouds[source] = {"text": [new_text]}
return wordclouds
However, when I run the function, I get None
for the text
list as shown below.
>>> w = {}
>>> w = update(w, 'fred', 'I am happy')
>>> w
{'fred': {'text': ['I am happy']}}
>>> w = update(w, 'fred', 'I am not happy')
>>> w
{'fred': {'text': None}}
>>>
The first pass through the function gives the expected result: {'fred': {'text': ['I am happy']}}
. But the second call to the function for some reason returns None
for the text
field in the dictionary. I expected {'fred': {'text': ['I am happy', 'I am not happy']}}
If I change the code to be this:
def update(wordclouds, source, new_text):
if source in wordclouds:
#old_text = wordclouds[source]['text']
#frank = old_text.append(new_text)
wordclouds[source]['text'].append(new_text)
else:
wordclouds[source] = {"text": [new_text]}
return wordclouds
It works as expected:
>>> w = {}
>>> w = update(w, 'fred', 'I am happy')
>>> w
{'fred': {'text': ['I am happy']}}
>>> w = update(w, 'fred', 'I am not happy')
>>> w
{'fred': {'text': ['I am happy', 'I am not happy']}}
>>>
I must be missing something very basic about dictionaries and fucntions, but I just don't see it. Why is the text
list set to None
in the second call to the first example of the update
function, and not the second?
Thanks!