Access Dict Via Dict.key
Solution 1:
You can implement a custom dict
wrapper (either a subclass of dict
or something that contains a dict
) and implement __getattr__
(or __getattribute__
) to return data from the dict
.
classDictObject(object):def__init__(self, data):
self.mydict = data
def__getattr__(self, attr):
if attr inself.mydict:returnself.mydict[attr]
returnsuper(self, DictObject).__getattr__(attr)
Solution 2:
I'm a beginner myself, but let me try and answer:
Say you have a dictionary:
dictionary = {"One": 1, "Two": 2, "Three": 3}
You can create a class with its keys like:
classDictKeys:
One = 'One'
Two = 'Two'
Three = 'Three'
Here, One, Two and Three are class variables or attributes, which means if you create an object for this class:
key = DictKeys()
You can access all of those keys using the '.' (dot) operator.
key.One
>>'One'
Now just plug it where ever you want to access your dictionary!
dictionary[key.One]
>>1
I'm sure this isn't the best way, and class access is a tiny bit slower than dict access, but if you really want to, you can access all your keys with a dot using this method.
Solution 3:
The correct way to access a dictionary is how you proposed it:
source['livemode']
Post a Comment for "Access Dict Via Dict.key"