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 次浏览

启动你的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.