programing tip

Python에서 dict의 사전을 초기화하는 가장 좋은 방법은 무엇입니까?

itbloger 2020. 10. 9. 09:02
반응형

Python에서 dict의 사전을 초기화하는 가장 좋은 방법은 무엇입니까?


이 질문에 이미 답변이 있습니다.

Perl에서 여러 번 다음과 같이 할 것입니다.

$myhash{foo}{bar}{baz} = 1

이것을 파이썬으로 어떻게 번역합니까? 지금까지 :

if not 'foo' in myhash:
    myhash['foo'] = {}
if not 'bar' in myhash['foo']:
    myhash['foo']['bar'] = {}
myhash['foo']['bar']['baz'] = 1

더 좋은 방법이 있습니까?


class AutoVivification(dict):
    """Implementation of perl's autovivification feature."""
    def __getitem__(self, item):
        try:
            return dict.__getitem__(self, item)
        except KeyError:
            value = self[item] = type(self)()
            return value

테스트 :

a = AutoVivification()

a[1][2][3] = 4
a[1][3][3] = 5
a[1][2]['test'] = 6

print a

산출:

{1: {2: {'test': 6, 3: 4}, 3: {3: 5}}}

필요한 중첩 양이 고정되어 collections.defaultdict있으면 훌륭합니다.

예를 들어 두 개의 깊은 중첩 :

myhash = collections.defaultdict(dict)
myhash[1][2] = 3
myhash[1][3] = 13
myhash[2][4] = 9

다른 수준의 중첩을 수행하려면 다음과 같은 작업을 수행해야합니다.

myhash = collections.defaultdict(lambda : collections.defaultdict(dict))
myhash[1][2][3] = 4
myhash[1][3][3] = 5
myhash[1][2]['test'] = 6

편집 : MizardX는 간단한 함수로 완전한 일반성을 얻을 수 있다고 지적합니다.

import collections
def makehash():
    return collections.defaultdict(makehash)

이제 다음을 수행 할 수 있습니다.

myhash = makehash()
myhash[1][2] = 4
myhash[1][3] = 8
myhash[2][5][8] = 17
# etc

dicts의 dict가 필요한 이유가 있습니까? 특정 구조에 대한 설득력있는 이유가 없다면 튜플을 사용하여 dict를 간단히 인덱싱 할 수 있습니다.

mydict = {('foo', 'bar', 'baz'):1} # Initializes dict with a key/value pair
mydict[('foo', 'bar', 'baz')]      # Returns 1

mydict[('foo', 'unbar')] = 2       # Sets a value for a new key

The parentheses are required if you initialize the dict with a tuple key, but you can omit them when setting/getting values using []:

mydict = {}                        # Initialized the dict
mydict['foo', 'bar', 'baz'] = 1    # Sets a value
mydict['foo', 'bar', 'baz']        # Returns 1

I guess the literal translation would be:

 mydict = {'foo' : { 'bar' : { 'baz':1}}}

Calling:

 >>> mydict['foo']['bar']['baz']

gives you 1.

That looks a little gross to me, though.

(I'm no perl guy, though, so I'm guessing at what your perl does)

참고URL : https://stackoverflow.com/questions/651794/whats-the-best-way-to-initialize-a-dict-of-dicts-in-python

반응형