how to safely extract dict values
David Zaret
dave at zaret.com
Mon Jul 31 07:20:34 EDT 2006
thanks for the many responses.
i have zero control over the dict. in practice, i'm using turbogears
which is "automatically" populating the result dict with zero-to-many
choices from a generated list of HTML checkboxes. the user can select
none, one, or many, and submit. cherrypy packs the **kwargs arg full of
the selection, as i described in my op.
using a try/exception case to switch between append and extend will not
work. the scalar, coming back as a string, can certainly be iterated
and i'll end up with a bunch of characters in my list.
i like what's posted below - that's more compact - and at least closer
to what i was looking for.
thanks again, great newsgroup.
---- dz
Bruno Desthuilliers wrote:
> 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
>
More information about the Python-list
mailing list