[Tutor] append value to dictionary key

Alan Gauld alan.gauld at btinternet.com
Fri Mar 6 19:53:17 CET 2015


On 06/03/15 14:28, Chris Stinemetz wrote:
> I would like to append a value to a dictionary key where there is already a
> value. Something like the below:
>
> d = {'name': {'2': 0.0, '7': 10.0, '8': 0.0, '9': 0.0}}
> append 10 to d['name']['2']
> d = {'name': {'2': 0.0,10, '7': 10.0, '8': 0.0, '9': 0.0}}
>
> When I try to this I get the following error:
>>>> d['name']['2'].append(10)
> Traceback (most recent call last):
>    File "<stdin>", line 1, in <module>
> AttributeError: 'float' object has no attribute 'append'


To append a value you need a list.
So put the values of the dictionary in lists.

d = {'name': {'2': [0.0], '7': [10.0], '8': [0.0], '9': [0.0]}}

Now your

d['name']['2'].append(10)

will work and produce:.

d = {'name': {'2': [0.0, 10], '7': [10.0], '8': [0.0], '9': [0.0]}}

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list