how to safely extract dict values

Bruno Desthuilliers onurb at xiludom.gro
Mon Jul 31 06:44:52 EDT 2006


David Zaret 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:
>             .....
> 
> 
> my way is ugly.  what's a better way?

If you have control over the dict's creation and 'filling', you may want
to handle the case there - eventually using a custom dict-like object
that stores everything (but None) in lists. The implementation code for
this object will not be less ugly than the one above, but at least
ugliness will be hidden away !-)

Else, you can shorten the code a bit (NB : ignoring the 'None' case...):

  v = d[k]
  v = ([v], v)[isinstance(v, list)]

And this can be hidden away in a function:

def get_as_list(d, k):
  v = d[k]
  return ([v], v)[isinstance(v, list)]

vals = get_as_list(mydict, mykey)


I don't like using isinstance() tests too much, but it depends on the
context...

HTH

-- 
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