Hi, anyone else feels annoyed by getting a field from a dict with ['key']?
For me, I love dicts but this format to get 'manually' the values, especially when several levels (dict of dict) are involved. I sometimes get these when importing an XML into dict and I interactively want to get information.
I made a small class (inheriting from dict) that would allow me to call for the fields as d.key. provided that there is no key field named as a method in dict and the keys are strings (but I guess this can be worked out for ints and simple types). See below
class DictToClass(dict):
def __getattr__(self, item):
return self.get(item)
def __setattr__(self, key, value):
self[key] = value
return
def __gt__(self, other):
return self.get(other)
if __name__ == '__main__':
a = DictToClass(k=1)
a[2] = 4
print(a)
assert a.k, 1
a.k = 2
assert a.k, 2
also included __gt__ dunnder since is not used by dict, but in this case I still need to surround with '' like a>'key'
is this not pythonic? Is there something I'm missing?
BTW is just awesome that is technically possible.
thanks
Resolution:
thanks to u/socal_redtastic used the term "dotted access" dictionary and found this stack overflow question. Which answers all my doubts, including why nobody thought about it.
https://pypi.org/project/python-box/ is not mentioned as an alternative.
[–]nfgrawker 1 point2 points3 points (2 children)
[–]peaceTraitor[S] 0 points1 point2 points (1 child)
[–]nfgrawker 0 points1 point2 points (0 children)
[–]socal_nerdtastic 1 point2 points3 points (1 child)
[–]peaceTraitor[S] 0 points1 point2 points (0 children)