Make Python dictionaries accessible as attributes

Thing you want to do

I'm not sure if the title can express what I want to do correctly, but the point is that sometimes I want to do something like this. Especially after writing JS. ..

d = dict(a=1, b=2)

#Usually used like this
d["c"] = d["a"] + d["b"]

#I like this feeling
d.c = d.a + d.b

Answer

You can extend the dictionary a little and map __setattr__ to __setitem__ (get too). Happy!

sklearn.datasets.base.Bunch

bonus

By becoming an attribute, completion will work on IPython. For example, if you are using the requests module, when you say "I want to see the contents of the current response header!", Candidates will be displayed in a row just by tabs.


import requests
from sklearn.datasets.base import Bunch as dict

#Try hitting the GitHub API
response = requests.get("https://api.github.com")
headers = dict(**response.headers)

If you do header. <TAB> in this state ...

スクリーンショット 2017-02-19 2.49.59.png

Because of this, the number of strokes can be reduced considerably compared to hitting headers [" X-RateLimit-Remaining"] etc. one by one. Wow! !! from··

スクリーンショット 2017-02-19 3.12.07.png

Oh ... oh ...

Recommended Posts

Make Python dictionaries accessible as attributes
Alternative: Make Python dictionaries accessible as attributes
Make Python dict accessible by Attribute
Python3 | Lists, Tuples, Dictionaries
Python lists, tuples, dictionaries
Make MeCab available from Python3
Make Jupyter Lab accessible remotely
Make Puyo Puyo AI with Python
Don't make test.py in Python!
Make a bookmarklet in Python
Make a fortune with Python
Make Opencv available in Python
Make python segfault in 2 lines
Try to make capture software with as high accuracy as possible with python (1)