Concise idiom to initialize dictionaries
Peter Otten
__peter__ at web.de
Tue Nov 9 14:12:15 EST 2004
Frohnhofer, James wrote:
> My initial problem was to initialize a bunch of dictionaries at the start
> of a function.
>
> I did not want to do
> def fn():
> a = {}
> b = {}
> c = {}
> . . .
> z = {}
> simply because it was ugly and wasted screen space.
Here is a bunch of dictionaries that spring into existence by what is
believed to be magic :-)
>>> class AllDicts:
... def __getattr__(self, name):
... d = {}
... setattr(self, name, d)
... return d
... def __repr__(self):
... items = self.__dict__.items()
... items.sort()
... return "\n".join(map("%s -> %r".__mod__, items))
...
>>> ad = AllDicts()
>>> ad.a[1] = 99
>>> ad.b[2] = 42
>>> ad.b[3] = 11
>>> ad
a -> {1: 99}
b -> {2: 42, 3: 11}
Peter
More information about the Python-list
mailing list