Le jeudi 24 août 2006 21:02, Fredrik Lundh a écrit : > class wrapper: > def __init__(self, dict): > self.dict = dict > def __getitem__(self, key): > try: > return self.dict[key] > except KeyError: >
Quite the same idea, but without eval and the need to know the internal dict arborescence : In [242]: class nested_dict_wrapper : .....: def __init__(self, dic) : .....: self._all = [dic] + [nested_dict_wrapper(v) for v in dic.values() if isinstance(v, dict)] .....: def __getitem__(self, v) : .....: for i in self._all : .....: try : return i[v] .....: except KeyError: pass .....: raise KeyError(v + ' not found in dict and subdicts') .....: .....: In [248]: complex_dict = { '0': 'zero', '1':'one', 'in1' : {'2':'two'}, 'in2': {'3': 'three', '4' :'four', 'deeper':{'5':'five', '6':'six'}}, '7':'seven' } In [250]: "%%(%s)s "*7 % tuple(range(7)) % nested_dict_wrapper(complex_dict) Out[250]: 'zero one two three four five six ' In [251]: "%%(%s)s "*8 % tuple(range(8)) % nested_dict_wrapper(complex_dict) Out[251]: 'zero one two three four five six seven ' In [252]: "%%(%s)s "*9 % tuple(range(9)) % nested_dict_wrapper(complex_dict) --------------------------------------------------------------------------- exceptions.KeyError Traceback (most recent call last) /home/maric/<ipython console> /home/maric/<ipython console> in __getitem__(self, v) KeyError: '8 not found in dict and subdicts' -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 -- http://mail.python.org/mailman/listinfo/python-list