map -> class instance

Mark McEahern marklists at mceahern.com
Wed Jun 12 18:32:03 EDT 2002


> I want to convert dictionary instances to instances of a class that
> has the keys of the map as attributes.

Try this:

class mapper:

    def __str__(self):
        s = "<mapper>"
        for k, v in self.__dict__.items():
            s += "<%s>%s</%s>" % (k, v, k)
        s += "</mapper>"
        return s

    __repr__ = __str__

def map2class(d):
    m = mapper()
    for k, v in d.items():
        setattr(m, k, v)
    return m

d = {'first' : 'John',
     'last' : 'Hunter',
     'age' : 34}

x = map2class(d)

print x

**
Or, slightly different:
**

class mapper:

    def __init__(self, d=None):
        if d:
            for k, v in d.items():
                setattr(self, k, v)

    def __str__(self):
        s = "<mapper>"
        for k, v in self.__dict__.items():
            s += "<%s>%s</%s>" % (k, v, k)
        s += "</mapper>"
        return s

    __repr__ = __str__

d = {'first' : 'John',
     'last' : 'Hunter',
     'age' : 34}

x = mapper(d)

print x


-






More information about the Python-list mailing list