programing

명명된 튜플을 사전으로 변환

copysource 2023. 2. 3. 23:22
반응형

명명된 튜플을 사전으로 변환

나는 파이톤이라는 이름의 튜플 수업이 있다.

class Town(collections.namedtuple('Town', [
    'name', 
    'population',
    'coordinates',
    'population', 
    'capital', 
    'state_bird'])):
    # ...

타운 인스턴스를 사전으로 변환하고 싶습니다.마을의 이름이나 밭 수에 얽매이지 않았으면 좋겠어요.

필드를 추가하거나 전혀 다른 이름을 가진 튜플을 전달하여 사전을 얻을 수 있는 방법이 있습니까?

원래 클래스 정의는 다른 사용자의 코드에 있으므로 변경할 수 없습니다.그래서 마을의 예를 들어 사전으로 변환해야 합니다.

TL;DR: 방법이 있습니다._asdict준비했습니다.

다음은 사용 예시를 보여드리겠습니다.

>>> fields = ['name', 'population', 'coordinates', 'capital', 'state_bird']
>>> Town = collections.namedtuple('Town', fields)
>>> funkytown = Town('funky', 300, 'somewhere', 'lipps', 'chicken')
>>> funkytown._asdict()
OrderedDict([('name', 'funky'),
             ('population', 300),
             ('coordinates', 'somewhere'),
             ('capital', 'lipps'),
             ('state_bird', 'chicken')])

이것은 명명된 튜플의 문서화된 방식입니다. 즉, python의 일반적인 규칙과는 달리 메서드 이름의 선두 밑줄은 사용을 권장하지 않습니다.명명된 튜플에 추가된 다른 방법들과 함께_make,_replace,_source,_fields필드명과의 경합을 방지하기 위해서만 밑줄이 붙어 있습니다.


주의: 야생에 있는 일부 2.7.5 < python version < 3.5.0 코드에서는 다음 버전이 표시될 수 있습니다.

>>> vars(funkytown)
OrderedDict([('name', 'funky'),
             ('population', 300),
             ('coordinates', 'somewhere'),
             ('capital', 'lipps'),
             ('state_bird', 'chicken')])

한동안 문서에는 다음과 같은 내용이 기재되어 있었습니다._asdict는 더 이상 사용되지 않으며(여기를 참조), 내장된 메서드 vars 사용을 제안합니다.이 조언은 이제 구식이 되었습니다.서브클래싱과 관련된 버그를 수정하기 위해__dict__명명된 튜플에 존재했던 속성이 이 커밋에 의해 다시 제거되었습니다.

에 내장된 방법이 있습니다.namedtuple인스턴스, 입니다.

댓글에서 설명한 바와 같이 일부 버전에서는vars()또, 빌드 디테일에 크게 의존하고 있는 것 같습니다만,_asdict신뢰할 수 있어야 합니다.버전에 따라서는_asdict는 권장되지 않는 것으로 표시되어 있습니다만, 코멘트에 의하면, 3.4를 기점으로 이 상황은 해소되고 있습니다.

보통._asdict()a를 반환하다OrderedDict. 이것은 에서 변환하는 방법입니다.OrderedDict정례에dict


town = Town('funky', 300, 'somewhere', 'lipps', 'chicken')
dict(town._asdict())

출력은 다음과 같습니다.

{'capital': 'lipps',
 'coordinates': 'somewhere',
 'name': 'funky',
 'population': 300,
 'state_bird': 'chicken'}

Ubuntu 14.04 LTS 버전의 python2.7 및 python3.4에서는__dict__자산이 예상대로 작동했습니다._asdict 메서드도 작동했지만 현지화된 비균일 API 대신 표준 정의 균일한 속성 API를 사용하는 경향이 있습니다.

python 2.7달러

# Works on:
# Python 2.7.6 (default, Jun 22 2015, 17:58:13)  [GCC 4.8.2] on linux2
# Python 3.4.3 (default, Oct 14 2015, 20:28:29)  [GCC 4.8.4] on linux

import collections

Color = collections.namedtuple('Color', ['r', 'g', 'b'])
red = Color(r=256, g=0, b=0)

# Access the namedtuple as a dict
print(red.__dict__['r'])  # 256

# Drop the namedtuple only keeping the dict
red = red.__dict__
print(red['r'])  #256

dict로 보는 것은 (적어도 내가 아는 한) 모든 것을 나타내는 사전을 얻을 수 있는 의미적 방법이다.


주요 Python 버전 및 플랫폼과 그 지원의 표를 축적하면 좋을 것입니다.__dict__현재 위에 게시된 것과 같이 플랫폼 버전은 1개, 파이썬 버전은 2개뿐입니다.

| Platform                      | PyVer     | __dict__ | _asdict |
| --------------------------    | --------- | -------- | ------- |
| Ubuntu 14.04 LTS              | Python2.7 | yes      | yes     |
| Ubuntu 14.04 LTS              | Python3.4 | yes      | yes     |
| CentOS Linux release 7.4.1708 | Python2.7 | no       | yes     |
| CentOS Linux release 7.4.1708 | Python3.4 | no       | yes     |
| CentOS Linux release 7.4.1708 | Python3.6 | no       | yes     |

케이스 1: 1차원 태플

TUPLE_ROLES = (
    (912,"Role 21"),
    (913,"Role 22"),
    (925,"Role 23"),
    (918,"Role 24"),
)


TUPLE_ROLES[912]  #==> Error because it is out of bounce. 
TUPLE_ROLES[  2]  #==> will show Role 23.
DICT1_ROLE = {k:v for k, v in TUPLE_ROLES }
DICT1_ROLE[925] # will display "Role 23" 

: 2: 2차원 튜플
예: DICT_ROLES #에는 '가 표시됩니다.DICT_ROLES[961] # ' 、 「 DICT _ ROLES 」

NAMEDTUPLE_ROLES = (
    ('Company', ( 
            ( 111, 'Owner/CEO/President'), 
            ( 113, 'Manager'),
            ( 115, 'Receptionist'),
            ( 117, 'Marketer'),
            ( 119, 'Sales Person'),
            ( 121, 'Accountant'),
            ( 123, 'Director'),
            ( 125, 'Vice President'),
            ( 127, 'HR Specialist'),
            ( 141, 'System Operator'),
    )),
    ('Restaurant', ( 
            ( 211, 'Chef'), 
            ( 212, 'Waiter/Waitress'), 
    )),
    ('Oil Collector', ( 
            ( 211, 'Truck Driver'), 
            ( 213, 'Tank Installer'), 
            ( 217, 'Welder'),
            ( 218, 'In-house Handler'),
            ( 219, 'Dispatcher'),
    )),
    ('Information Technology', ( 
            ( 912, 'Server Administrator'),
            ( 914, 'Graphic Designer'),
            ( 916, 'Project Manager'),
            ( 918, 'Consultant'),
            ( 921, 'Business Logic Analyzer'),
            ( 923, 'Data Model Designer'),
            ( 951, 'Programmer'),
            ( 953, 'WEB Front-End Programmer'),
            ( 955, 'Android Programmer'),
            ( 957, 'iOS Programmer'),
            ( 961, 'Back-End Programmer'),
            ( 962, 'Fullstack Programmer'),
            ( 971, 'System Architect'),
    )),
)

#Thus, we need dictionary/set

T4 = {}
def main():
    for k, v in NAMEDTUPLE_ROLES:
        for k1, v1 in v:
            T4.update ( {k1:v1}  )
    print (T4[961]) # will display 'Back-End Programmer'
    # print (T4) # will display all list of dictionary

main()

no_incitict의 경우 다음과 같이 사용할 수 있습니다.

def to_dict(model):
    new_dict = {}
    keys = model._fields
    index = 0
    for key in keys:
        new_dict[key] = model[index]
        index += 1

    return new_dict

파이썬 3사전에 필요한 인덱스로 필드에 사전 할당, '이름'을 사용했습니다.

import collections

Town = collections.namedtuple("Town", "name population coordinates capital state_bird")

town_list = []

town_list.append(Town('Town 1', '10', '10.10', 'Capital 1', 'Turkey'))
town_list.append(Town('Town 2', '11', '11.11', 'Capital 2', 'Duck'))

town_dictionary = {t.name: t for t in town_list}

언급URL : https://stackoverflow.com/questions/26180528/convert-a-namedtuple-into-a-dictionary

반응형