Python — Namedtuple
文章簡介
- Namedtuple背景介紹
- 修改Namedtuple裡的attributes
- 修改Namedtuple裡的class fields
- 設定Namedtuple default values
- Namedtuple的應用 — Namedtuplify the dictionary
Namedtuple背景介紹
Why Namedtuple
Namedtuple是Python中一個獨特的資料結構,首先的問題是: 為什麼我們需要使用Namedtuple:
管理物件時,相較於一般tuple,Namedtuple多加上了一層attribute layer, 當需要access一個物件的某個attribute時,我們不需要特別去記哪個index代表何種tuple的何種attribute:
STUDENT_A = ("John", "Chen", "001", "177CM", "70KG", "Male")print(STUDENT_A[0]) #John,取出First name
print(STUDENT_A[3]) #177CM,取出身高
print(STUDENT_A[5]) #Male,取出性別
在這個例子中,我們建構了一個tuple去管理學生資料,但必須去記每個attribute被存在index的何處。
而這時可能會想,用class會簡單的多:
class STUDENT:
def __init__(self, first_name, last_name, student_number, height, weight, gender): self.first_name = first_name
self.last_name = last_name
self.student_number = student_number
self.height = height
self.weight = weight
self.gender = genderSTUDENT_A = STUDENT("John", "Chen", "001", "177CM", "70KG", "Male")
print(STUDENT_A.first_name)
print(STUDENT_A.height)
print(STUDENT_A.gender)
使用class的好處就是可以直接用attribute去取資料,然後class依然有兩個缺陷:
- 需要自定義許多基本的method在物件上,例如表示物件的__repr__、比較物件的__eq__…等等。
- class物件預設情況下是可以被修改的資料型態,當我們不希望使用者去更改特定attribute時,除了把attribute寫成private外,也可以考慮使用Namedtuple。
#自定義__repr__
def __repr__(self):
return f"STUDENT's first_name is {self.first_name}, second_name is {self.last_name})"#自定義__eq__
def __eq__(self, other):
if isinstance(other, STUDENT):
return self.first_name == other.first_name and self.last_name == other.last_name
else:
return FalseSTUDENT_A = STUDENT("John", "Chen", "001", "177CM", "70KG", "Male")
STUDENT_B = STUDENT("Josh", "Wang", "002", "174CM", "72KG", "Male")print(STUDENT_A.__repr__())
#STUDENT's first name is John, second name is Chenprint(STUDENT_A == STUDENT_B)
#Call STUDENT_A.__eq__, False
綜合以上,我們有了使用Namedtuple的三個原因、因為他兼融了tuple與class的優點:
1. Namedtuple像class一樣有一層物件的attribute layer,能夠去取物件的attribute值
2. Namedtuple是tuple的一個子集合,是不可變的資料型態,因此不會被修改
3. Namedtuple已經有representation及equal(比較)的物件特性
Namedtuple Constructor
namedtuple_class = namedtuple(“name of Namedtuple”, “fields name of Namedtuple”) → return a class
namedtuple_object = namedtuple_class(attribute_name mapping to field names)
Namedtuple constructor需要傳入兩個arguments,第一個argument是這個Namedtuple的名稱,第二個argument是Namedtuple的fields/attributes,可以使用:
- an list of strings(“[,]”)
- a tuple of strings(“(,)”)
- a single string separate by space or comma(“field1 field2”)or (“field1, field2)
#用Namedtuple建構物件
from collections import namedtuple
STUDENT_CLASS = namedtuple("STUDENT_CLASS", ["first_name","last_name", "student_number", "height", "weight", "gender"])
STUDENT_A = STUDENT_CLASS("John", "Chen", "001", "177CM", "70KG", "Male")#看這個Namedtuple類型的所有fields
print(STUDENT_CLASS._fields) #("first_name", "last_name", "student_number", "height", "weight", "gender")#Access物件的特定attribute
print(STUDENT_A.first_name) #John
print(STUDENT_A.height) #177CM
print(STUDENT_A.gender) #Male#Using getattr去access物件的特定attribute
print(getattr(STUDENT_A, "height"))
修改Namedtuple裡的attributes
Namedtuple是不可變的資料結構,不過若我們想要修改其中的資料,有幾種方式可以implement:
- Unpack — Change Foodstyle attribute
#Set the namedtuple class
CITIES_CLASS = namedtuple("CITIES_CLASS", "Country, City, Population, President, Foodstyle, Language")#Set the namedtuple object
Taipei = CITIES_CLASS("Taiwan", "Taipei", 2300000000, "Tsai", "Taiwanese", "Chinese")#Unpack the namedtuple
*other, foodstyle, language = Taipei#Recreate Taipei, Change the Foodstyle
Taipei = CITIES_CLASS(*other, "Traditional style", language)
這邊使用tuple可以被unpack的特性去取出值,並且重複利用被unpack的值,只針對Foodstyle去做重新賦值。
Get John’s stories in your inbox
Join Medium for free to get updates from this writer.
2. Slicing — Change Language attribute
unchange_part = Taipei[:5]
new_tuple_information = unchange_part + ('English',) #要有逗點才會被認為是Tuple#Recreate Taipei, Change the English
Taipei = CITIES_CLASS(*new_tuple_information)
因為tuple slicing的結果也會是tuple,而們前面有說到namedtuple class的第二個argument可以傳入tuple,所以這邊要讓新的namedtuple object去沿用其他不需要被修改的部分,直接用tuple + tuple = tuple的規則加上新的tuple資料就好。
3. Using the _replace method — Change President attribute
Taipei = Taipei._replace(President="Ma") #使用Keyword argument去修改attribute這個方法是最簡潔的修改attribute方法,不過要注意,這邊在調用_replace method相當於是去複製舊有Namedtuple物件的部分attribute後,組合Keyword arguments的新attribute,創造新的Namedtuple物件,而不是單純修改原Namedtuple物件:
Taipei = CITIES_CLASS("Taiwan", "Taipei", 2300000000, "Tsai", "Taiwanese", "Chinese")
print(id(Taipei))Taipei = Taipei._replace(President = "Ma")
print("changing attribute.....")
print(id(Taipei))>> 1410440649840 #原本物件的memory address
>> changin attribute
>> 1410443225344 #新物件的memory address
修改Namedtuple裡的class fields
除了修改既有的attribute之外,若想要新增Namedtuple的class field,可以先用前面提到的._fields method取出原本的所有class fields,再加上新的即可:
new_fields = CITIES_CLASS._fields + ("People",)
EXT_CITIES_CLASS = namedtuple("EXT_CITIES_CLASS", new_fields)設定Namedtuple default values
在定義Namedtuple class時,有一些fields我們想要預先寫入default的attribute值,這時候有兩種方法可以implement:
- Set .__new__.__defaults__ — Set default values for Foodstyle and Language
#Set the namedtuple class
CITIES_CLASS = namedtuple("CITIES_CLASS", "Country, City, Population, President, Foodstyle, Language")#Set the default value for Foodstyle and Language
CITIES_CLASS.__new__.__defaults__ = ("American","English") #Provide a tuple and right align with your parameters#No need to give value for Foodstyle and Language
New_York= CITIES_CLASS(USA,Taipei,8460000,Biden")
2. Set Keyword argument when constructing Namedtuple class — Set default values for Foodstyle and Language
#Set the default value for Foodstyle and Language when constructing Namedtuple
CITIES_CLASS = namedtuple("CITIES_CLASS", "Country, City, Population, President, Foodstyle, Language", defaults=("American","English"))#No need to give value for Foodstyle and Language
New_York= CITIES_CLASS(USA,Taipei,8460000,Biden")
Namedtuple的應用 — Namedtuplify the dictionary
想要達成的目的:使用Namedtuple的資料結構去轉換原先用Dictionary貯存的一系列資料,並且若某資料缺失某個attribute,則該attribute為None。
原先資料:
data_list = [{"key1": 1, "key2":2},{"key1":3, "key2":4},{"key1":5, "key2":6, "key3":7},{"key2":100}]- Step1: 把資料中所有出現過的key做成一個Namedtuple的fields
key_set = set()
for dictionary in data_list:
for key in dictionary.keys():
key_set.add(key)
Struct = namedtuple("Struct", sorted(key_set))2. Step2: 設定每個fields的default value為None
Struct.__new__.__defaults__ = (None,) * len((Struct._fields))3. Step3: 轉換資料為一系列的Namedtuple
tuple_list = []
for convert_dictionary in data_list:
tuple_list.append(Struct(**convert_dictionary))
print(tuple_list)>> [Struct(key1=1, key2=2, key3=None), Struct(key1=3, key2=4, key3=None), Struct(key1=5, key2=6, key3=7), Struct(key1=None, key2=100, key3=None)]
完成轉換為我們可以把這整個過程寫成一個Function,重複利用:
def tuplify_dict(target_dict):
key_set = set()
for dictionary in target_dict:
for key in dictionary.keys():
key_set.add(key)
Struct = namedtuple("Struct", sorted(key_set))
Struct.__new__.__defaults__ = (None,) * len((Struct._fields))
converted_tuple_list = [Struct(**dict_item) for dict_item in target_dict]
return converted_tuple_list
print(tuplify_dict(data_list))>> [Struct(key1=1, key2=2, key3=None), Struct(key1=3, key2=4, key3=None), Struct(key1=5, key2=6, key3=7), Struct(key1=None, key2=100, key3=None)]







