티스토리 뷰

반응형

Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.

Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.

 

아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.

How to use a dot "." to access members of dictionary?

점 "."을 사용하여 딕셔너리 멤버에 접근하는 방법은?

 문제 내용 

How do I make Python dictionary members accessible via a dot "."?

어떻게 점 "."을 사용하여 딕셔너리 멤버에 접근 할 수 있나요?

 

For example, instead of writing mydict['val'], I'd like to write mydict.val.

예를 들어, mydict['val'] 대신에 mydict.val 처럼 작성하고 싶습니다.

 

Also I'd like to access nested dicts this way. For example

또한 이 방법으로 중첩된 딕셔너리에도 접근하고 싶습니다. 예를 들어 가래 코드는
mydict.mydict2.val 

 

would refer to

이는 다음과 같이 나타낼 수 있습니다.
mydict = { 'mydict2': { 'val': ... } }

 

 

 높은 점수를 받은 Solution 

I've always kept this around in a util file. You can use it as a mixin on your own classes too.

항상 유틸 파일에서 이를 유지해왔습니다. 자신의 클래스에 믹스인으로 사용할 수도 있습니다.
class dotdict(dict):
    """dot.notation access to dictionary attributes"""
    __getattr__ = dict.get
    __setattr__ = dict.__setitem__
    __delattr__ = dict.__delitem__

mydict = {'val':'it works'}
nested_dict = {'val':'nested works too'}
mydict = dotdict(mydict)
mydict.val
# 'it works'

mydict.nested = dotdict(nested_dict)
mydict.nested.val
# 'nested works too'

 

 

 가장 최근 달린 Solution 

I dislike adding another log to a (more than) 10-year old fire, but I'd also check out the dotwiz library, which I've recently released - just this year actually.

(10년 이상 된 불쌍한 불에) 한 조각 더 넣는 것은 싫지만, 최근에 출시한 dotwiz 라이브러리도 확인해보시는 걸 추천드립니다.

 

It's a relatively tiny library, which also performs really well for get (access) and set (create) times in benchmarks, at least as compared to other alternatives.

이 라이브러리는 다른 대안들과 비교해서 적은 크기의 라이브러리이지만, get(액세스)과 set(생성) 시간 측면에서 매우 높은 성능을 보여줍니다.

 

Install dotwiz via pip

pip를 사용하여 dotwiz를 설치하십시오.
pip install dotwiz

 

It does everything you want it to do and subclasses dict, so it operates like a normal dictionary:

이 코드는 당신이 원하는 모든 것을 수행하고 일반적인 딕셔너리처럼 작동하기 때문에 dict를 상속합니다.
from dotwiz import DotWiz

dw = DotWiz()
dw.hello = 'world'
dw.hello
dw.hello += '!'
# dw.hello and dw['hello'] now both return 'world!'
dw.val = 5
dw.val2 = 'Sam'

 

On top of that, you can convert it to and from dict objects:

게다가, 당신은 그것을 dict 객체로 변환하고 dict 객체로부터 DotWiz로 변환할 수 있습니다.
d = dw.to_dict()
dw = DotWiz(d) # automatic conversion in constructor

 

This means that if something you want to access is already in dict form, you can turn it into a DotWiz for easy access:

이것은 당신이 액세스하려는 것이 이미 dict 형식으로 있는 경우, 쉬운 액세스를 위해 DotWiz로 바꿀 수 있음을 의미합니다.
import json
json_dict = json.loads(text)
data = DotWiz(json_dict)
print data.location.city

 

Finally, something exciting I am working on is an existing feature request so that it automatically creates new child DotWiz instances so you can do things like this:

마지막으로, 나는 새로운 자식 DotWiz 인스턴스를 자동으로 만들어 이렇게 할 수 있도록 하는 기능 요청을 처리하고 있어 매우 흥미롭게 작업하고 있습니다.
dw = DotWiz()
dw['people.steve.age'] = 31

dw
# ✫(people=✫(steve=✫(age=31)))

 

Comparison with dotmap

dotmap과의 비교

 

I've added a quick and dirty performance comparison with dotmap below.

아래에서 dotmap과의 빠른 성능 비교를 추가했습니다.

 

First, install both libraries with pip:

먼저 pip로 두 라이브러리를 설치하세요.
pip install dotwiz dotmap

 

I came up with the following code for benchmark purposes:

성능 측정을 위한 다음 코드를 생각해냈습니다.
from timeit import timeit

from dotwiz import DotWiz
from dotmap import DotMap


d = {'hey': {'so': [{'this': {'is': {'pretty': {'cool': True}}}}]}}

dw = DotWiz(d)
# ✫(hey=✫(so=[✫(this=✫(is=✫(pretty={'cool'})))]))

dm = DotMap(d)
# DotMap(hey=DotMap(so=[DotMap(this=DotMap(is=DotMap(pretty={'cool'})))]))

assert dw.hey.so[0].this['is'].pretty.cool == dm.hey.so[0].this['is'].pretty.cool

n = 100_000

print('dotwiz (create):  ', round(timeit('DotWiz(d)', number=n, globals=globals()), 3))
print('dotmap (create):  ', round(timeit('DotMap(d)', number=n, globals=globals()), 3))
print('dotwiz (get):  ', round(timeit("dw.hey.so[0].this['is'].pretty.cool", number=n, globals=globals()), 3))
print('dotmap (get):  ', round(timeit("dm.hey.so[0].this['is'].pretty.cool", number=n, globals=globals()), 3))

 

Results, on my M1 Mac, running Python 3.10:

결과는, Python 3.10을 실행하는 M1 Mac에서 다음과 같습니다.
dotwiz (create):   0.189
dotmap (create):   1.085
dotwiz (get):   0.014
dotmap (get):   0.335

 

 

출처 : https://stackoverflow.com/questions/2352181/how-to-use-a-dot-to-access-members-of-dictionary

반응형
댓글
공지사항
최근에 올라온 글