# python神級數據結構namedtuple

`from collections import namedtuple`

namedtuple實際上是靈活的創建了一個對象而不是tuple. tuple的功能主要是爲了賦值用.直接舉例子

## 基本用法

``````>>> # Basic example
>>> Point = namedtuple('Point', ['x', 'y'])
>>> p = Point(11, y=22)     # instantiate with positional or keyword arguments
# >>> p = Point(11, 22)
>>> p[0] + p[1]             # indexable like the plain tuple (11, 22)
33
>>> x, y = p                # unpack like a regular tuple
>>> x, y
(11, 22)
>>> p.x + p.y               # fields also accessible by name
33
>>> p                       # readable __repr__ with a name=value style
Point(x=11, y=22)
``````

## 經典用法

``````EmployeeRecord = namedtuple('EmployeeRecord', 'name, age, title, department, paygrade')

import sqlite3
conn = sqlite3.connect('/companydata')
cursor = conn.cursor()
cursor.execute('SELECT name, age, title, department, paygrade FROM employees')
for emp in map(EmployeeRecord._make, cursor.fetchall()):
print(emp.name, emp.title)
``````

`classmethodsomenamedtuple._make`(iterable)

``````>>> t = [11, 22]
>>> Point._make(t)
Point(x=11, y=22)
``````

## 神級用法

`somenamedtuple.`_asdict`()`

``````>>> p = Point(x=11, y=22)
>>> p._asdict()
{'x': 11, 'y': 22}
``````

``````EmployeeRecord = namedtuple('EmployeeRecord', 'name, age, title, department, paygrade')

import sqlite3
conn = sqlite3.connect('/companydata')
cursor = conn.cursor()
cursor.execute('SELECT name, age, title, department, paygrade FROM employees')
for emp in map(EmployeeRecord._make, cursor.fetchall()):
print(emp._asdict())
``````