Adding to an Array inside a Dict

Robert Kern robert.kern at gmail.com
Mon Oct 11 11:22:00 EDT 2010


On 10/11/10 9:55 AM, MacOSX @ Rocteur.cc wrote:
> Hi,
>
> Is there an easier way to do this, I am adding/creating to an array inside a
> dict but can find a cleaner way:
>
> So I first check if the key exists already, if it does then I know I use append,
> if it does not I create it.
>
>          if osmdict.has_key(token):
>              osmdict[token]['user'].append(user)
>              osmdict[token]['reason'].append(reason)
>          else:
>              osmdict[token] = { 'user' : [user], 'reason' : [reason]}

http://docs.python.org/library/collections#collections.defaultdict

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco




More information about the Python-list mailing list