how to safely extract dict values

David Zaret dave at zaret.com
Sun Jul 30 23:35:41 EDT 2006


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?

thanks,

---- dz



More information about the Python-list mailing list