Append a new value to dict

Tim Chase python.list at tim.thechases.com
Mon Oct 13 14:39:15 CEST 2008


>> In Python, this is the best code I could come up with for 
>> adding a new key, value to a dict
>> 
>> mytable.setdefault( k, [] ).append( v )
> 
> Naturally, right after writing my post I found that there is
> an easier way:
> 
> table[ k ] = v

Just to be clear...these do two VERY different things:

   >>> v1=42
   >>> table1={}
   >>> k='foo'
   >>> table1.setdefault(k,[]).append(v1)
   >>> table2={}
   >>> table2[k]=v1
   >>> table1, table2
   ({'foo': [42]}, {'foo': 42})

Note that the value in the first case is a *list* while the
value in the 2nd case, the value is a scalar.  These differ in 
the behavior (continuing from above):

   >>> v2='Second value'
   >>> table1.setdefault(k,[]).append(v2)
   >>> table2[k]=v2
   >>> table1, table2
   ({'foo': [42, 'Second value']}, {'foo': 'Second value'})

Note that table1 now has *two* values associated with 'foo', 
while table2 only has the most recently assigned value.

Choose according to your use-case.  For some of my ETL & 
data-processing work, I often want the

   mydict.setdefault(key, []).append(value)

version to accrue values associated with a given unique key.

-tkc









More information about the Python-list mailing list