1. 程式人生 > >Python程式設計:namedtuple命名元組和dict字典相互轉換

Python程式設計:namedtuple命名元組和dict字典相互轉換

from collections import namedtuple

dct = {
    "name": "Tom",
    "age": 24
}

Person = namedtuple("Person", ["name", "age"])

# 字典轉為namedtuple
person = Person._make(dct)
print(person)
# Person(name='name', age='age')

# namedtuple轉為字典
print(person._asdict())
# OrderedDict([('name', 'name'), ('age', 'age')])

其實namedtuple繼承自OrderedDict有序字典