how to safely extract dict values

Bruno Desthuilliers onurb at xiludom.gro
Mon Jul 31 06:46:45 EDT 2006


Amit Khemka wrote:
> On 7/31/06, David Zaret <dave at zaret.com> wrote:
>> i have a dict with a particular key - the values for this key will be
>> None, one valid scalar, or a list:
>>
>>         {mykey, None}
>>         {mykey, "foo"}
>>         {mykey, ["bar", "baz"]}
>>
>> let's ignore the None case - in the case of the one or many values, i
>> want to suck the values into a list.  here's one way to do this:
>>
>>              if mydict.has_key(mykey):
>>                  vals=[]
>>                  _v = mydict[mykey]
>>                  if isinstance(_v, types.ListType):
>>                      vals.extend(_v)
>>                  else:
>>                      vals.append(_v)
>>                  #   now we can safely iterate through acts
>>                 for val in vals:
>>                         .....
> 
> how about:
> 
> vals = []
> for val in mydict.values():
>   try: vals.extend(val)
>   except: vals.append(val)

>>> l = []
>>> l.extend((1, 2))
>>> l
[1, 2]
>>> l.extend('ab')
>>> l
[1, 2, 'a', 'b']
>>>


-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"



More information about the Python-list mailing list