Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Represent a class as a dict or list

I've classes that is used for getting data from one system, making some modifications and then outputting them into another system. Which usually goes the way of converting it into a dict or a list after I've made all the necessary conversions.

So far what I've done is that I've made two methods called as_dict() and as_list() and used that whenever I need that representation.

But I'm curious if there's a way to be able to do dict(instance_of_my_class) or list(instance_of_my_class).

I've been reading up on magic methods and it seems as if this is not possible?

And some simple sample code to work with:

class Cost(object):
    @property
    def a_metric(self):
        return self.raw_data.get('a_metric', 0) * 0.8

    [..]
    # Repeat for various kinds of transformations

    def as_dict(self):
        return {
          'a_metric': self.a_metric,
          [...]
        }
like image 949
gaqzi Avatar asked Apr 25 '13 06:04

gaqzi


People also ask

How do I turn a class into a dictionary in Python?

By using the __dict__ attribute on an object of a class and attaining the dictionary. All objects in Python have an attribute __dict__, which is a dictionary object containing all attributes defined for that object itself. The mapping of attributes with its values is done to generate a dictionary.

Should I use dict () or {}?

tl;dr. With CPython 2.7, using dict() to create dictionaries takes up to 6 times longer and involves more memory allocation operations than the literal syntax. Use {} to create dictionaries, especially if you are pre-populating them, unless the literal syntax does not work for your case.

Is dict better than list?

The dictionary is preferred because of less time and less space storage as dictionaries are implemented in the form of hash tables from python3.

What is __ dict __ method?

The __dict__ in Python represents a dictionary or any mapping object that is used to store the attributes of the object. They are also known as mappingproxy objects. To put it simply, every object in Python has an attribute that is denoted by __dict__.


1 Answers

Do you mean something like this? If so you have to define a __iter__ method that yield's key-value pairs:

In [1]: class A(object):
   ...:     def __init__(self):
   ...:        self.pairs = ((1,2),(2,3))
   ...:     def __iter__(self):
   ...:         return iter(self.pairs)
   ...:     

In [2]: a = A()

In [3]: dict(a)
Out[3]: {1: 2, 2: 3}

Also, it seems that dict tries to call the .keys / __getitem__ methods before __iter__, so you can make list(instance) and dict(instance) return something completely different.

In [4]: class B(object):
    ...:     def __init__(self):
    ...:        self.d = {'key':'value'}
    ...:        self.l = [1,2,3,4]
    ...:     def keys(self):
    ...:         return self.d.keys()
    ...:     def __getitem__(self, item):
    ...:         return self.d[item]
    ...:     def __iter__(self):        
    ...:         return iter(self.l)
    ...:     

In [5]: b = B()

In [6]: list(b)
Out[6]: [1, 2, 3, 4]

In [7]: dict(b)
Out[7]: {'key': 'value'}
like image 89
root Avatar answered Sep 18 '22 23:09

root