Python中將巢狀字典轉換為對映元組
巢狀字典是一種分層資料結構,其中值本身被稱為字典。它允許在基本字典記憶體儲多個字典。對映元組由元組集合定義,其中各個元組包含成對的值。將一種形式轉換為另一種形式意味著將鍵值對之間的更改設定為元組列表。在 Python 中,我們將使用一些內建函式,例如 `isinstance()`、`extend()`、`append()` 和 `str()` 來將巢狀字典轉換為對映元組。
語法
以下語法用於示例:
isintance()
`isinstance()` 是 Python 中一個內建函式,用於檢查第一個引數是否是第二個引數的子類或例項。
extend()
`extend()` 是 Python 中一個內建方法,用於在當前列表的末尾新增指定的元素。
append()
`append()` 是 Python 中一個內建方法,它接受一個元素作為輸入引數,將其新增到給定列表的末尾。
str()
內建函式 `str()` 透過將引數值轉換為值的形式來定義。
使用遞迴
在下面的示例中,程式使用遞迴函式來管理一些內建函式——`extend()` 和 `append()`,它們將巢狀字典轉換為對映元組。
示例
def dict_mapped_tup(dictionary): map_tuple = [] for key, value in dictionary.items(): if isinstance(value, dict): map_tuple.extend((key, subkey, subvalue) for subkey, subvalue in dict_mapped_tup(value)) else: map_tuple.append((key, value)) return map_tuple # Create the nested dictionary nes_dict = { "key 1": "50", "key 2": { "subkey 1": "10", "subkey 2": "20" }, "key 3": "60" } # Calling function mapped_tup = dict_mapped_tup(nes_dict) print(mapped_tup)
輸出
[('key 1', '50'), ('key 2', 'subkey 1', '10'), ('key 2', 'subkey 2', '20'), ('key 3', '60')]
使用遞迴生成器和 `isinstance()`
在下面的示例中,程式使用遞迴生成器,它充當常規函式,這意味著函式自身正在呼叫。然後使用內建函式 `isinstance()`,它接受兩個引數來檢查第一個引數是否是第二個引數的子類。
示例
def dict_mapped_tup(dictionary): for key, value in dictionary.items(): if isinstance(value, dict): yield from ((key,) + subkey_value for subkey_value in dict_mapped_tup(value)) else: yield key, value # Create the nested dictionary nested_dict = { "key1": "100", "key2": { "subkey1": "200", "subkey2": "300", "subkey3": "400" }, "key3": "500" } # Calling function map_tuple = list(dict_mapped_tup(nested_dict)) print(map_tuple)
輸出
[('key1', '100'), ('key2', 'subkey1', '200'), ('key2', 'subkey2', '300'), ('key2', 'subkey3', '400'), ('key3', '500')]
使用字典操作
在下面的示例中,程式使用字典操作以及列表、元組和 for 迴圈,遍歷給定列表以將巢狀字典轉換為對映元組。
示例
# Create the nested dictionary my_dict = {'Tutorials' : {'x' : 10, 'y' : 20}, 'is' : {'x' : 100, 'y' : 400}, 'good' : {'x' : 80, 'y' : 63}} # Display the original dictionary print("Original Dictionary: " + str(my_dict)) # Using dictionary operation result = [(key, tuple(my_dict[k][key] for k in my_dict)) for key in my_dict['Tutorials']] # Display the output print("The Combined dictionary: " + str(result))
輸出
Original Dictionary: {'Tutorials': {'x': 10, 'y': 20}, 'is': {'x': 100, 'y': 400}, 'good': {'x': 80, 'y': 63}} The Combined dictionary: [('x', (10, 100, 80)), ('y', (20, 400, 63))]
結論
我們討論瞭解決此問題陳述的各種方法。以上兩個示例使用了遞迴函式,這意味著函式自身正在呼叫,而第三個示例顯示了使用列表和元組的字典操作。這種型別的程式碼有助於根據資料排列構建邏輯。
廣告