Python程式將字典值轉換為字串


在 Python 中,**字典**是一個無序的鍵值對集合。它是一種資料結構,允許您根據與每個值關聯的唯一鍵儲存和檢索值。字典中的鍵用於唯一地標識值,並且必須是不可變的,例如字串、數字或元組。另一方面,字典中關聯的值可以是任何資料型別,並且可以是可變的。

當我們想要將字典值轉換為字串時,我們需要使用迴圈遍歷字典,並使用 str() 函式將每個值分別轉換為字串。

輸入輸出場景

請檢視以下輸入輸出場景,以瞭解將字典值轉換為字串的概念。

Input dictionary: {'red': 3, 'yellow': 2, 'green': 3}
Output convered dictionary: {'red': '3', 'yellow': '2', 'green': '3'}

轉換後的字典包含原始鍵及其相應的值(已轉換為字串)。

Input dictionary:
{'k1': 12, 'numbers': [1, 2, 3], 'tuple of numbers': (10, 11, 2)}
 
Output convered dictionary:
{'k1': '12', 'numbers': '[1, 2, 3]', 'tuple of numbers': '(10, 11, 2)'}

在轉換後的字典中,整數 12、列表 [1, 2, 3] 和元組 (10, 11, 2) 分別轉換為字串 '12'、'[1, 2, 3]' 和 '(10, 11, 2)'。

在本文中,我們將瞭解將字典值轉換為字串的不同方法。

使用 for 迴圈

在這種方法中,我們將使用轉換後的值更新原始字典中的字串。我們將使用 for 迴圈中的 items() 方法遍歷原始字典,併為每個值使用 str() 函式將其轉換為字串。

示例

以下是一個示例,演示如何使用 str() 函式和 for 迴圈將字典值轉換為字串。

# Create the dictionary 
dictionary = {'red': 3, 'yellow': 2, 'green': 3}
print('Input dictionary:', dictionary)

for key, value in dictionary.items():
    dictionary[key] = str(value)
    
# Display the output
print('Output convered dictionary:', dictionary)

輸出

Input dictionary: {'red': 3, 'yellow': 2, 'green': 3}
Output convered dictionary: {'red': '3', 'yellow': '2', 'green': '3'}

使用字典推導式

與之前的方法相同,這裡我們將使用字典推導式建立一個名為 converted_dict 的新字典。我們將使用 items() 方法遍歷原始字典,併為每個鍵值對使用 str() 函式將值轉換為字串。然後將生成的鍵值對新增到 converted_dict 中。

示例

以下是一個示例,演示如何使用字典推導式將字典值轉換為字串。

# Create the dictionary 
dictionary = {'k1': 123, 'numbers': [1, 2, 3], 'tuple of numbers': (10, 11, 2)}
print('Input dictionary:')
print(dictionary)

converted_dict = {key: str(value) for key, value in dictionary.items()}

# Display the output
print('Output convered dictionary:')
print(converted_dict)

輸出

Input dictionary:
{'k1': 123, 'numbers': [1, 2, 3], 'tuple of numbers': (10, 11, 2)}
Output convered dictionary:
{'k1': '123', 'numbers': '[1, 2, 3]', 'tuple of numbers': '(10, 11, 2)'}

使用 join() 方法

在這種方法中,我們將把字典值轉換為單個字串。這裡我們使用 .join() 方法將所有值連線到一個字串中。表示式 "".join() 指定一個空字串作為值之間的分隔符。

示例

以下是如何將字典值轉換為單個字串的示例。

# Create the dictionary 
dictionary = {1:'t', 2:'u', 3:'t', 4:'o', 5:'r', 6:'i', 7:'a', 8:'l', 9:'s', 10:'p', 11:'o', 12:'i', 13:'n', 14:'t'}
print('Input dictionary:')
print(dictionary)

converted_dict = "".join(v for _,v in dictionary.items())

# Display the output
print('Output convered string:')
print(converted_dict)

輸出

Input dictionary:
{1: 't', 2: 'u', 3: 't', 4: 'o', 5: 'r', 6: 'i', 7: 'a', 8: 'l', 9: 's', 10: 'p', 11: 'o', 12: 'i', 13: 'n', 14: 't'}
Output convered string:
tutorialspoint

更新於: 2023年8月29日

494 次瀏覽

啟動你的 職業生涯

透過完成課程獲得認證

開始學習
廣告