[Tutor] appending/updating values dict key value pairs
Albert-Jan Roskam
fomcl at yahoo.com
Sat Jun 22 21:39:53 CEST 2013
________________________________
> From: Sivaram Neelakantan <nsivaram.net at gmail.com>
>To: tutor at python.org
>Sent: Saturday, June 22, 2013 7:52 PM
>Subject: Re: [Tutor] appending/updating values dict key value pairs
>
>
>On Sat, Jun 22 2013,Mark Lawrence wrote:
>
>
>[snipped 7 lines]
>
>>>>>> b = { 'a': [4, 5]}
>>>>>> list.append(b.get('a'),'c')
>>>>>> b
>>> {'a': [4, 5, 'c']}
>>>>>>
>>>
>>>
>>> as in, shouldn't it be
>>>
>>> b['a'] = list.append(b.get('a'),'c')
>>>
>>> which doesn't seem to work.
>>>
>>> sivaram
>>> --
>>
>> b['a'].append('c')
>
>
>arrgh! I should have known this. Thank you for making it obvious to
>the noob.
I use dict.setdefault fairly often for things like this:
>>> d = {}
>>> d.setdefault("aKey", []).append("aValue")
>>> d.setdefault("aKey", []).append("anotherValue")
>>> d
{'aKey': ['aValue', 'anotherValue']}
>>> d.setdefault("anotherKey", []).append("aValue")
>>> d
{'aKey': ['aValue', 'anotherValue'], 'anotherKey': ['aValue']}
More information about the Tutor
mailing list