Python vs dictionary key object attribute

Suppose I have an object with the key 'dlist0' with the attribute 'row_id', which I can access as

getattr(dlist0,'row_id')

then it returns a value but if I have a dictionary

ddict0 = {'row_id':4, 'name':'account_balance'}
getattr(ddict0,'row_id')

he does not work

My question is how can I access ddict0 and dlist0 in the same way

can anyone help me?

+3
source share
2 answers

Dictionaries have elements and, thus, use everything that is defined as __getitem__()to get the key value.

Objects have attributes and, therefore, are used __getattr__()to get the attribute value.

, - ? :

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)
+5

, namedtuple

>>> 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'}
+1

Source: https://habr.com/ru/post/1755259/


All Articles