在 Python 中將字典轉換為元組列表


在 Python 裡,從一種集合型別轉換成另一個集合型別是很常見的。根據資料處理的需求,我們可能必須轉換字典中成對的鍵值對,將其轉換成列表中表示元組的對。在這篇文章中,我們將瞭解實現此目的的方法。

使用 in

這是一個直接的方法,只需考慮

示例

 即時演示

Adict = {30:'Mon',11:'Tue',19:'Fri'}

# Given dictionary
print("The given dictionary: ",Adict)

# Using in
Alist = [(key, val) for key, val in Adict.items()]

# Result
print("The list of tuples: ",Alist)

輸出

執行以上程式碼,會得到以下結果 −

The given dictionary: {30: 'Mon', 11: 'Tue', 19: 'Fri'}
The list of tuples: [(30, 'Mon'), (11, 'Tue'), (19, 'Fri')]

使用 zip

zip 函式將傳給它的項作為引數合併起來。因此,我們取字典的鍵和值作為 zip 函式的引數,並將結果放在一個列表函式之下。鍵值對變成了列表的元組。

示例

 即時演示

Adict = {30:'Mon',11:'Tue',19:'Fri'}

# Given dictionary
print("The given dictionary: ",Adict)

# Using zip
Alist = list(zip(Adict.keys(), Adict.values()))

# Result
print("The list of tuples: ",Alist)

輸出

執行以上程式碼,會得到以下結果 −

The given dictionary: {30: 'Mon', 11: 'Tue', 19: 'Fri'}
The list of tuples: [(30, 'Mon'), (11, 'Tue'), (19, 'Fri')]

使用 append

在此方法中,我們取一個空列表,並將每一對鍵值以元組方式附加。設計一個 for 迴圈來將鍵值對轉換成元組。

示例

 即時演示

Adict = {30:'Mon',11:'Tue',19:'Fri'}

# Given dictionary
print("The given dictionary: ",Adict)

Alist = []

# Uisng append
for x in Adict:
k = (x, Adict[x])
Alist.append(k)

# Result
print("The list of tuples: ",Alist)

輸出

執行以上程式碼,會得到以下結果 −

The given dictionary: {30: 'Mon', 11: 'Tue', 19: 'Fri'}
The list of tuples: [(30, 'Mon'), (11, 'Tue'), (19, 'Fri')]

更新於: 2020 年 5 月 13 日

724 次瀏覽

開啟你的 職業

完成課程即可獲得認證

立即開始
廣告
© . All rights reserved.