Custom class to a dictionary?

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sat Jan 26 07:01:59 EST 2008


On Sat, 26 Jan 2008 03:35:18 -0800, Oliver Beattie wrote:

> Just wondering if it is possible to pass a custom class instance
> instance to dict() by way of using methods like you can for iterators
> (__iter__, __getitem__ etc.) I see there is no __dict__ -- is there
> anything else I can use to achieve this?


Just write a method to return (key, value) pairs, and call that:

>>> class Parrot(object):
...     def __init__(self):
...             self.keys = [1, 2, 3, 4]
...             self.values = ["one", "two", "three", "four"]
...     def generate_tuples(self):
...             for k,v in zip(self.keys, self.values):
...                     yield (k,v)
...
>>> p = Parrot()
>>> p.generate_tuples()
<generator object at 0xb7d1d78c>
>>> dict(p.generate_tuples())
{1: 'one', 2: 'two', 3: 'three', 4: 'four'}



Here's another way:

>>> class Foo(object):
...     def __getitem__(self, i):
...             if i > 4:
...                     raise IndexError
...             return (i, 'foo %d' % i)
...
>>> dict(Foo())
{0: 'foo 0', 1: 'foo 1', 2: 'foo 2', 3: 'foo 3', 4: 'foo 4'}



Bonus marks if you can explain why they both work :)

(Hint: consider the "sequence protocol" and the "iterator protocol".)



-- 
Steven



More information about the Python-list mailing list