Program Club

가변 깊이가있는 다단계 defaultdict?

proclub 2020. 12. 2. 22:09
반응형

가변 깊이가있는 다단계 defaultdict?


다음과 같은 큰 목록이 있습니다.

[A][B1][C1]=1
[A][B1][C2]=2
[A][B2]=3
[D][E][F][G]=4

다음과 같은 다단계 사전을 작성하고 싶습니다.

A
--B1
-----C1=1
-----C2=1
--B2=3
D
--E
----F
------G=4

재귀 defaultdict를 사용하면 table[A][B1][C1]=1, 를 쓸 수 있다는 것을 알고 table[A][B2]=2있지만이 삽입 문을 하드 코딩하는 경우에만 작동합니다.

목록을 구문 분석하는 동안을 (를) 호출하기 위해 사전에 필요한 []의 수를 알 수 없습니다 table[key1][key2][...].


클래스를 정의하지 않고도 할 수 있습니다.

from collections import defaultdict

nested_dict = lambda: defaultdict(nested_dict)
nest = nested_dict()

nest[0][1][2][3][4][5] = 6

귀하의 예는 모든 수준에서 값과 하위 요소의 사전이있을 수 있다고 말합니다. 이를 트리 라고하며 이를위한 많은 구현이 있습니다. 이것은 하나입니다.

from collections import defaultdict
class Tree(defaultdict):
    def __init__(self, value=None):
        super(Tree, self).__init__(Tree)
        self.value = value

root = Tree()
root.value = 1
root['a']['b'].value = 3
print root.value
print root['a']['b'].value
print root['c']['d']['f'].value

출력 :

1
3
None

JSON으로 입력을 작성하고을 사용하여 json.load중첩 된 사전의 구조로 읽음 으로써 비슷한 작업을 수행 할 수 있습니다.


나는 dict그 정의 의 하위 클래스로 그것을 할 것입니다 __missing__.

>>> class NestedDict(dict):
...     def __missing__(self, key):
...             self[key] = NestedDict()
...             return self[key]
...
>>> table = NestedDict()
>>> table['A']['B1']['C1'] = 1
>>> table
{'A': {'B1': {'C1': 1}}}

defaultdict는 초기화시 팩토리 함수예상 하기 때문에 defaultdict로 직접 수행 할 수 없지만 초기화시에는 동일한 defaultdict를 설명 할 방법이 없습니다. 위의 구조는 기본 dict와 동일한 작업을 수행하지만 명명 된 클래스 (NestedDict)이므로 누락 된 키가 발견되면 자신을 참조 할 수 있습니다. defaultdict를 하위 클래스로 만들고 재정의하는 것도 가능합니다 __init__.


재귀 사전의 가장 간단한 구현은 이것이라고 생각합니다. 리프 노드 만 값을 포함 할 수 있습니다.

# Define recursive dictionary
from collections import defaultdict
tree = lambda: defaultdict(tree)

용법:

# Create instance
mydict = tree()

mydict['a'] = 1
mydict['b']['a'] = 2
mydict['c']
mydict['d']['a']['b'] = 0

# Print
import prettyprint
prettyprint.pp(mydict)

산출:

{
  "a": 1, 
  "b": {
    "a": 1
  }, 
  "c": {},
  "d": {
    "a": {
      "b": 0
    }
  }
}

이것은 위와 동일하지만 람다 표기법을 피합니다. 읽기가 더 쉬울까요?

def dict_factory():
   return defaultdict(dict_factory)

your_dict = dict_factory()

또한-주석에서-기존 dict에서 업데이트하려면 다음을 호출하면됩니다.

your_dict[0][1][2].update({"some_key":"some_value"})

dict에 값을 추가하기 위해.


Dan O'Huiginn posted a very nice solution on his journal in 2010:

http://ohuiginn.net/mt/2010/07/nested_dictionaries_in_python.html

>>> class NestedDict(dict):
...     def __getitem__(self, key):
...         if key in self: return self.get(key)
...         return self.setdefault(key, NestedDict())


>>> eggs = NestedDict()
>>> eggs[1][2][3][4][5]
{}
>>> eggs
{1: {2: {3: {4: {5: {}}}}}}

A slightly different possibility that allows regular dictionary initialization:

from collections import defaultdict

def superdict(arg=()):
    update = lambda obj, arg: obj.update(arg) or obj
    return update(defaultdict(superdict), arg)

Example:

>>> d = {"a":1}
>>> sd = superdict(d)
>>> sd["b"]["c"] = 2

To add to @Hugo
To have a max depth:

l=lambda x:defaultdict(lambda:l(x-1)) if x>0 else defaultdict(dict)
arr = l(2)

You may achieve this with a recursive defaultdict.

from collections import defaultdict

def tree():
    def the_tree():
        return defaultdict(the_tree)
    return the_tree()

It is important to protect the default factory name, the_tree here, in a closure ("private" local function scope). Avoid using a one-liner lambda version, which is bugged due to Python's late binding closures, and implement this with a def instead.

The accepted answer, using a lambda, has a flaw where instances must rely on the nested_dict name existing in an outer scope. If for whatever reason the factory name can not be resolved (e.g. it was rebound or deleted) then pre-existing instances will also become subtly broken:

>>> nested_dict = lambda: defaultdict(nested_dict)
>>> nest = nested_dict()
>>> nest[0][1][2][3][4][6] = 7
>>> del nested_dict
>>> nest[8][9] = 10
# NameError: name 'nested_dict' is not defined

Have table['A']=defaultdict().

참고URL : https://stackoverflow.com/questions/5369723/multi-level-defaultdict-with-variable-depth

반응형