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

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's gravatar image

Eduardo
2212516
accept rate: 33%

closed 28 Mar '12, 04: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 Answers:

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

link

answered 27 Mar '12, 15:39

JohanG-Sweden's gravatar image

JohanG-Sweden
9.4k1242100

Thanks @JohanG.

(28 Mar '12, 04:29) Eduardo Eduardo's gravatar image

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.

link

answered 27 Mar '12, 15:40

Peter%20Collingridge's gravatar image

Peter Collin...
1.7k835

edited 27 Mar '12, 15:41

Thank you for your help Peter.

(28 Mar '12, 04:32) Eduardo Eduardo's gravatar image

Markdown Basics

  • *italic* or _italic_
  • **bold** or __bold__
  • link:[text](http://url.com/ "Title")
  • 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

Tags:

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

Asked: 27 Mar '12, 15:33

Seen: 237 times

Last updated: 28 Mar '12, 04:33