Dynamically get dict elements via getattr?

2024/9/27 12:16:02

I want to dynamically query which objects from a class I would like to retrieve. getattr seems like what I want, and it performs fine for top-level objects in the class. However, I'd like to also specify sub-elements.

class MyObj(object):def __init__(self):self.d = {'a':1, 'b':2}self.c = 3myobj = MyObj()
val = getattr(myobj, "c")
print val # Correctly prints 3
val = getattr(myobj, "d['a']") # Seemingly incorrectly formatted query
print val # Throws an AttributeError

How can I get the object's dictionary elements via a string?

Answer

The reason you're getting an error is that getattr(myobj, "d['a']") looks for an attribute named d['a'] on the object, and there isn't one. Your attribute is named d and it's a dictionary. Once you have a reference to the dictionary, then you can access items in it.

mydict = getattr(myobj, "d")
val    = mydict["a"]

Or as others have shown, you can combine this in one step (I showed it as two to better illustrate what is actually happening):

val = getattr(myobj, "d")["a"]

Your question implies that you think that items of a dictionary in an object are "sub-elements" of the object. An item in a dictionary, however, is a different thing from an attribute of an object. (getattr() wouldn't work with something like o.a either, though; it just gets one attribute of one object. If that's an object too and you want to get one of its attributes, that's another getattr().)

You can pretty easily write a function that walks an attribute path (given in a string) and attempts to resolve each name either as a dictionary key or an attribute:

def resolve(obj, attrspec):for attr in attrspec.split("."):try:obj = obj[attr]except (TypeError, KeyError):obj = getattr(obj, attr)return obj

The basic idea here is that you take a path and for each component of the path, try to find either an item in a dictionary-like container or an attribute on an object. When you get to the end of the path, return what you've got. Your example would be resolve(myobj, "d.a")

https://en.xdnf.cn/q/71453.html

Related Q&A

How do I copy an image from the output in Jupyter Notebook 7+?

Ive been working with Jupyter Notebooks for quite a while. When working with visualisations, I like to copy the output image from a cell by right clicking the image and selecting "Copy Image"…

How to join 2 dataframe on year and month in Pandas?

I have 2 dataframe and I want to join them on the basis of month and year from a date without creating extra columns:example :df1 :date_1 value_1 2017-1-15 20 2017-1-31 30 2016-2-15 20df2…

Sorting Python Dictionary based on Key? [duplicate]

This question already has answers here:How do I sort a dictionary by key?(33 answers)Closed 10 years ago.I have created a python dictionary which has keys in this form :11, 10, 00, 01, 20, 21, 31, 30T…

Flask: Template in Blueprint Inherit from Template in App?

Im a total Flask/Jinja2 newbie, so maybe Im overlooking something obvious, but:Shouldnt Flask, out of the box, allow a template that exists in a blueprints templates/ folder to extend a base template d…

Equivalent of python2 chr(int) in python3

# python2 print(chr(174)) ?# python3 print(chr(174)) Im looking for the equivalent of chr() from python2. I believe this is due to python 3 returning unicode characters rather than ASCII.

How To Pagination Angular2 with Django Rest Framework API

I am trying to create a simple blog application using Angular2 with Django Rest Framework. I am implementing pagination in Django, but I do not know how to rendering it in Angular.API has the following…

Color percentage in image for Python using OpenCV

Im creating a code which can detect the percentage of green colour from an image. . I have a little experience with OpenCV but am still pretty new to image processing and would like some help with my c…

Combination of GridSearchCVs refit and scorer unclear

I use GridSearchCV to find the best parameters in the inner loop of my nested cross-validation. The inner winner is found using GridSearchCV(scorer=balanced_accuracy), so as I understand the documentat…

stale association proxy, parent object has gone out of scope with Flask-SQLAlchemy

Ive actually never encountered this error before:sqlalchemy.exc.InvalidRequestError: stale association proxy, parent object has gone out of scopeAfter doing some research, it looks like its because the…

Automatic dictionary key resolution with nested schemas using Marshmallow

I have a Marshmallow schema where an objects use a key to refer to an object that is defined in a dictionary in another part of the structure. I want to have the key automatically resolved when deseria…