I didn't know at the time of writing, but if you just want to access the dict by attribute, attrdict is Don Pisha.
It can be used as follows (quoted from the official document)
from attrdict import AttrDict a = AttrDict({'foo': 'bar'}) a.foo
'bar'
a['foo'] 'bar'
# Overview and motivation
When handling the Web-API response that returns json with python.
Generally, the hierarchy is deep, and it is troublesome to refer to it while checking the value for each hierarchy.
So, I thought it would be useful to have a _parse_ function that gives the following execution result.
```python
some_dict = {
"path":{
"to":{
"target":
"key": 1 }}}
# expected return: 1
parse(some_dict, "/path/to/target/key")
# expected return: None
parse(some_dict, "/fake/key")
It feels like a kind of query parser in terms of operation.
――If you use recursion, you can write it quickly. ――I thought it would be nice if you could refer to it like a path format, but the point is to write a split that supports dictionary type. --If the delimiter is fixed to "/", it will break if the key is "a / b". --If so, it is OK if the delimiter can be specified in kwarg format.
Minimal implementation.
d = {
'a': 1,
'b': [1, 2, 3],
'c': {
'ca': 1,
'cb': [2, 3, 4] }}
d2 = {
'a': 1,
'a/x': 2,
'b': {
'ba': 100 }}
def dparse(dic, p, sep="/", default=None):
lis = p.split(sep)
def _(dic, lis, sep, default):
if len(lis) == 0:
return default
if len(lis) == 1:
return dic.get(lis[0], default)
else:
return _(dic.get(lis[0], {}), lis[1:], sep, default)
return _(dic, lis, sep=sep, default=None)
if __name__=="__main__":
print dparse(d, "a") # 1
print dparse(d, "c/cb") # [2, 3, 4]
print dparse(d2, "a/x", sep=":") # 2
print dparse(d2, "b:ba", sep=":") # 100
Name dparse appropriately with an image that makes dict parse.
There should be various loopholes, so I'm waiting for Tsukkomi. The quick idea is that this function will break if it contains "None as value". It is a logical error source because it is not possible to distinguish between "non-existent" and "None as a value". The essence is the same because the default argument is specified other than None.
It may be better to raise the "non-existent" case obediently.
I think that a utility of this level is probably a reinvention of the wheel, so I would like to know if there is an existing good means to achieve this purpose.
The code or design is awkward, write this! We welcome your suggestions.
I chose dparse for the function name because I couldn't think of an appropriate name, but I couldn't express the name as a body, so if I had a good idea.
Recommended Posts