user3214546
user3214546

Reputation: 6831

Is there any way to use get with object instead of dict in python

If i have dictionary the this works fine

value = d.get(key, "empty")

But if d is my django model object then i get this

object has no attribute 'get'

How can i fix that. I want have same behaviour like dict to get empty if key does not exist

Upvotes: 1

Views: 87

Answers (1)

catavaran
catavaran

Reputation: 45575

Use getattr():

value = getattr(d, key, "empty")

Another option is to direct access to the object's __dict__:

value = d.__dict__.get(key, "empty")

But I suggest to use the getattr().

UPDATE: Note that getattr(some_dict, key) is not the same as the some_dict.get(key). getattr() gets the object's attribute but not the value of the dict.

Upvotes: 6

Related Questions