在Python中将字典添加到元组
当需要将字典添加到元组时,可以使用“列表”方法,“追加”和“元组”方法。
列表可用于存储异构值(即,任何数据类型的数据,例如整数,浮点数,字符串等)。
'append'方法将元素添加到列表的末尾。
以下是相同的演示-
示例
my_tuple_1 = (7, 8, 0, 3, 45, 3, 2, 22, 4)
print ("Thetupleis: " )
print(my_tuple_1)
my_dict = {"Hey" : 11, "there" : 31, "Jane" : 23}
print("Thedictionaryis: ")
print(my_dict)
my_tuple_1 = list(my_tuple_1)
my_tuple_1.append(my_dict)
my_tuple_1 = tuple(my_tuple_1)
print("Thetupleafteraddingthedictionaryelementsis: ")
print(my_tuple_1)输出结果Thetupleis:
(7, 8, 0, 3, 45, 3, 2, 22, 4)
Thedictionaryis:
{'Hey': 11, 'there': 31, 'Jane': 23}
Thetupleafteraddingthedictionaryelementsis:
(7, 8, 0, 3, 45, 3, 2, 22, 4, {'Hey': 11, 'there': 31, 'Jane': 23})解释
元组已定义并显示在控制台上。
字典已定义并显示在控制台上。
元组将转换为列表,然后使用“append”方法将字典添加到该列表中。
然后,将该结果数据转换为元组。
该结果分配给一个值。
它在控制台上显示为输出。