# [closed] Update the value in a pair key:value in a dictionary

 0 Hy everyone. I would like to ask for help in the following problem: I have a defined variable: dictionary={'apr2012': ['cs101'], 'feb2012': ['cs102']} And now, I want to update the value associated with 'apr2012' key appending 'cs382' string to ['cs101'] list. Then, dictionary would be something like this: dictionary={'apr2012': ['cs101','cs387'], 'feb2012': ['cs102']}. If I run this statement: dictionary['apr2012']=dictionary['apr2012'].append('cs387'), then dictionary={'apr2012': None, 'feb2012': ['cs102']}. Why does this happen? If I run dictionary['apr2012'].append('cs387') statement, then dictionary={'apr2012': ['cs101', 'cs387'], 'feb2012': ['cs102']}, which is correct. asked 27 Mar '12, 15:33 Eduardo 221●2●5●16 accept rate: 33%

### The question has been closed for the following reason "The question is answered, right answer was accepted" by Eduardo 28 Mar '12, 04:33

 2 This happens because append mutates the structure. It does not return a new structure. So when you do dictionary['apr2012']=dictionary['apr2012'].append('cs387')  ...you're saying "The value for the keyword 'apr2012' shall be whatever is returned from the append operation here". And append returns nothing, and therefore the result later is None. dictionary['apr2012'].append('cs387')  by itself get out the list and appends a new value to it, that is it actually changes the list that is the value of the keyword 'apr2012'. The irony of the first version is that you're doing an append, which is what you want, but then you throw away the value you just mutated and replaces it with nothing :-) answered 27 Mar '12, 15:39 JohanG-Sweden 9.4k●12●42●100 Thanks @JohanG. (28 Mar '12, 04:29) Eduardo
 1 The reason is that append is a function which returns None. Try: x = dictionary['apr2012'].append('cs387') print x  You will see that x is None. answered 27 Mar '12, 15:40 Peter Collin... 1.7k●8●35 Thank you for your help Peter. (28 Mar '12, 04:32) Eduardo

Markdown Basics

• *italic* or _italic_
• **bold** or __bold__
• image?![alt text](/path/img.jpg "Title")
• numbered list: 1. Foo 2. Bar
• to add a line break simply add two spaces to where you would like the new line to be.
• basic HTML tags are also supported

×15,282
×133
×57
×39
×26