how to safely extract dict values
Amit Khemka
khemkaamit at gmail.com
Mon Jul 31 06:35:41 EDT 2006
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)
cheers,
amit.
--
----
Amit Khemka -- onyomo.com
Home Page: www.cse.iitd.ernet.in/~csd00377
Endless the world's turn, endless the sun's Spinning, Endless the quest;
I turn again, back to my own beginning, And here, find rest.
More information about the Python-list
mailing list