在 Python 中将字典添加到元组
如果要将字典添加到元组中,可以使用 `list` 方法、`append` 方法和 `tuple` 方法。
可以使用列表来存储异类值(即任何数据类型的数据,例如整数、浮点、字符串等)。
`append` 方法将元素添加到列表末尾。
下面是对其进行演示−
示例
my_tuple_1 = (7, 8, 0, 3, 45, 3, 2, 22, 4)
print ("The tuple is : " )
print(my_tuple_1)
my_dict = {"Hey" : 11, "there" : 31, "Jane" : 23}
print("The dictionary is : ")
print(my_dict)
my_tuple_1 = list(my_tuple_1)
my_tuple_1.append(my_dict)
my_tuple_1 = tuple(my_tuple_1)
print("The tuple after adding the dictionary elements is : ")
print(my_tuple_1)输出
The tuple is :
(7, 8, 0, 3, 45, 3, 2, 22, 4)
The dictionary is :
{'Hey': 11, 'there': 31, 'Jane': 23}
The tuple after adding the dictionary elements is :
(7, 8, 0, 3, 45, 3, 2, 22, 4, {'Hey': 11, 'there': 31, 'Jane': 23})说明
- 定义了一个元组,并将其显示在控制台上。
- 定义了一个字典,并将其显示在控制台上。
- 将元组转换为列表,并使用 `append` 方法向其中添加字典。
- 然后,将此结果数据转换为元组。
- 此结果被赋予一个值。
- 它在控制台上作为输出显示。
广告
数据结构
网络
关系型数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP