MRAB <pyt...@mrabarnett.plus.com> writes:

> On 11/10/2010 15:55, 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]}
>>
>> Sorry if I've completely overlooked the obvious,
>>
>> Thanks in advance,
>>
> osmdict.setdefault(token, {}).update({'user': [user], 'reason': [reason]})

The above will overwrite the 'user' and 'reason' items in the osmdict[token]
dictionary if they already exist, which is not what the OP wants.

If osmdict can be a defaultdict you could do:

from collections import defaultdict

osmdict = defaultdict(defaultdict(list))

# Later, simply:
osmdict[token]['user'].append(user)
osmdict[token]['reason'].append(reason)

-- 
Arnaud
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to