將 Python 中的巢狀元組轉換為自定義鍵字典
當需要將巢狀元組轉換為自定義鍵字典時,可以使用列表解析。
以下是此演示:
示例
my_tuple = ((6, 'Will', 13), (2, 'Mark', 15), (9, 'Rob', 12)) print("Thw tuple is : ") print(my_tuple) my_result = [{'key': sub[0], 'value': sub[1], 'id': sub[2]} for sub in my_tuple] print("The converted dictionary is : ") print(my_result)
輸出
Thw tuple is : ((6, 'Will', 13), (2, 'Mark', 15), (9, 'Rob', 12)) The converted dictionary is : [{'key': 6, 'value': 'Will', 'id': 13}, {'key': 2, 'value': 'Mark', 'id': 15}, {'key': 9, 'value': 'Rob', 'id': 12}]
說明
定義元組的元組,並在控制檯上顯示。
列表解析用於遍歷元組。
字典中的鍵和值被指定為特定值,以及特定的 ID。
這被分配給一個變數。
它在控制檯上作為輸出顯示。
廣告