dict slice in python (translating perl to python)

Fredrik Lundh fredrik at pythonware.com
Thu Sep 11 13:11:13 EDT 2008


hofer wrote:

> The real example would be more like:
> 
> name,age,country = itemgetter('name age country'.split())(x)

ouch.

if you do this a lot (=more than once), just wrap your dictionaries in a 
simple attribute proxy, and use plain attribute access.  that is, given

     class AttributeWrapper:
         def __init__(self, obj):
             self.obj = obj
         def __getattr__(self, name):
             try:
                 return self.obj[name]
             except KeyError:
                 raise AttributeError(name)

or, shorter but less obvious and perhaps a bit too clever for a 
beginning Pythoneer:

     class AttributeWrapper:
         def __init__(self, obj):
             self.__dict__.update(obj)

you can do

 >>> some_data = dict(name="Some Name", age=123, country="SE")
 >>> some_data
{'country': 'SE', 'age': 123, 'name': 'Some Name'}

 >>> this = AttributeWrapper(some_data)
 >>> this.name
'Some Name'
 >>> this.age
123
 >>> this.country
'SE'

and, if you must, assign the attributes to local variables like this:

 >>> name, age, country = this.name, this.age, this.country
 >>> name
'Some Name'
 >>> age
123
 >>> country
'SE'
 >>>

(the next step towards true Pythonicness would be to store your data in 
class instances instead of dictionaries in the first place, but one step 
at a time...)

</F>




More information about the Python-list mailing list