Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python dictionary key Vs object attribute

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?

like image 509
Nazmul Hasan Avatar asked Jul 19 '10 07:07

Nazmul Hasan


People also ask

Can a dictionary key be an object Python?

Properties of Dictionary KeysThey can be any arbitrary Python object, either standard objects or user-defined objects.

What is attribute in dictionary Python?

AttrDict , Attribute Dictionary, is the exact same as a python native dict , except that in most cases, you can use the dictionary key as if it was an object attribute instead. This allows users to create container objects that looks as if they are class objects (as long as the user objects the proper limitations).

Are Python dictionaries the same as objects?

Difference between objects and dictionaries: The data stored in the form of key-value pairs is called an Object or a Dictionary. Objects and dictionaries are similar; the difference lies in semantics. In JavaScript, dictionaries are called objects, whereas, in languages like Python or C#, they are called dictionaries.

Can an object be dictionary key?

A dictionary key must be an immutable object. A dictionary value can be any object.


1 Answers

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)
like image 124
Amber Avatar answered Sep 25 '22 22:09

Amber