在 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` 方法向其中添加字典。
  • 然后,将此结果数据转换为元组。
  • 此结果被赋予一个值。
  • 它在控制台上作为输出显示。

更新于: 2021-03-11

4 千多浏览量

职业生涯起航

完成课程即可获得认证

开始
广告
© . All rights reserved.