1

Why can I not directly modify the list value in the following dict?

price_to_names = {'$': [], '$$': []}
price_to_names['$'] = price_to_names['$'].append('hello')

The following code changes the dict to

{'$': None, '$$': []}

I would like price_to_names to become

{'$': ['hello'], '$$': []}
Jeffrey Y.
  • 95
  • 4
  • 3
    Duplicate of http://stackoverflow.com/questions/16641119/why-does-append-return-none-in-this-code, http://stackoverflow.com/questions/20016802/why-the-list-append-return-none? – alecxe Jan 19 '16 at 14:30

1 Answers1

1

append does not return a new list, if modifies the list in place.

price_to_names['$'].append('hello') is None because the append method of a list returns None. This is why you are assigning None as the value for the key '$'. Don't use an assignment, just append to your list:

>>> price_to_names = {'$': [], '$$': []}
>>> price_to_names['$'].append('hello')
>>> price_to_names
{'$$': [], '$': ['hello']}
timgeb
  • 76,762
  • 20
  • 123
  • 145