0

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!

wjandrea
  • 28,235
  • 9
  • 60
  • 81
user1045680
  • 815
  • 2
  • 9
  • 19
  • 3
    The problem is here: `frank = old_text.append(new_text)`. Think about what `append` returns, and consequently what is being stored into `frank`, and then into the dictionary. – Carcigenicate May 16 '21 at 17:12

1 Answers1

1

list.append() returns None, therefore frank is None. For more info, see Why does append() always return None in Python?

Your second implementation of update() is correct, but in the same respect as list.append(), since it's mutating wordclouds, it shouldn't return wordclouds. And for what it's worth, you could simplify it using dict.setdefault():

def update(wordclouds, source, new_text):
    d = wordclouds.setdefault(source, {})
    d.setdefault("text", []).append(new_text)
>>> w = {}
>>> update(w, 'fred', 'I am happy')
>>> w
{'fred': {'text': ['I am happy']}}
>>> update(w, 'fred', 'I am not happy')
>>> w
{'fred': {'text': ['I am happy', 'I am not happy']}}
wjandrea
  • 28,235
  • 9
  • 60
  • 81