在 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` 方法向其中新增字典。
- 然後,將此結果資料轉換為元組。
- 此結果被賦予一個值。
- 它在控制檯上作為輸出顯示。
廣告