Reputation: 7040
suppose i have object has key 'dlist0' with attribute 'row_id' the i can access as
getattr(dlist0,'row_id')
then it return value but if i have a dictionary
ddict0 = {'row_id':4, 'name':'account_balance'}
getattr(ddict0,'row_id')
it is not work
my question is how can i access ddict0 and dlist0 same way
any one can help me?
Upvotes: 6
Views: 4522
Reputation: 14255
Although similar to @Amber's answer, the following is slightly more concise, and allows us to specify a default value. Gets either a dict
item or an object
attribute:
def get(*args):
_get = dict.get if type(args[0]) is dict else getattr
return _get(*args)
The arguments for dict.get
and getattr
are similar. Both accept an optional default value. Note, however, that getattr
raises an error if the attribute does not exist and default is not explicitly specified.
Some trivial examples:
>>> get({'my_key': 'my_value'}, 'my_key')
'my_value'
>>> class MyClass(object): pass
...
>>> get(MyClass(), 'my_attr_name', 'missing')
'missing'
Upvotes: 0
Reputation: 526583
Dictionaries have items, and thus use whatever is defined as __getitem__()
to retrieve the value of a key.
Objects have attributes, and thus use __getattr__()
to retrieve the value of an attribute.
You can theoretically override one to point at the other, if you need to - but why do you need to? Why not just write a helper function instead:
Python 2.x:
def get_value(some_thing, some_key):
if type(some_thing) in ('dict','tuple','list'):
return some_thing[some_key]
else:
return getattr(some_thing, some_key)
Python 3.x:
def get_value(some_thing, some_key):
if type(some_thing) in (dict,tuple,list):
return some_thing[some_key]
else:
return getattr(some_thing, some_key)
Upvotes: 9
Reputation: 304147
Perhaps a namedtuple is more suitable for your purpose
>>> from collections import namedtuple
>>> AccountBalance=namedtuple('account_balance','row_id name')
>>> ddict0=AccountBalance(**{'row_id':4, 'name':'account_balance'})
>>> getattr(ddict0,'row_id')
4
>>> ddict0._asdict()
{'row_id': 4, 'name': 'account_balance'}
Upvotes: 1