Checking if a variable is a dictionary
Neil Cerutti
mr.cerutti at gmail.com
Thu Mar 6 10:25:07 EST 2008
On Thu, Mar 6, 2008 at 8:06 AM, Guillermo
<guillermo.listas at googlemail.com> wrote:
> I want to iterate recursively a dictionary whose elements might be
> strings or nested tuples or dictionaries and then convert values to a
> tagged format according to some rules.
>
> d = {'a':"i'm a", 'b':(1,2,3),'c':{'a':"i'm a",'x':"something",'y':
> ('a','b','c')}}
This could be solved with dynamic polymorphism instead of
introspection, which might simplify things depending on how your
dictionary is constructed.
class Value(object):
def to_tagged_format(self):
raise NotImplementedError
class StringValue(Value):
def to_tagged_format(self):
...
class Tuplevalue(Value):
def to_tagged_format(self):
...
class DictValue(Value):
def to_tagged_format(self):
...
for k, v in d.iteritems():
d[k] = v.to_tagged_format()
You can also get the dynamic polymorphism without invoking inheritance
by specifying a protocol that the values in your dict must implement,
instead. Protocols are plentiful in Python, perhaps more popular than
type hierarchies.
--
Neil Cerutti <mr.cerutti+python at gmail.com>
More information about the Python-list
mailing list