在 Python 中將鍵值列表轉換為平面字典


當需要將包含鍵值對的字典轉換為平面列表時,可以使用字典推導。

它遍歷字典,並使用“zip”方法將它們打包。

zip 方法會採用可迭代物件,將其聚合到一個元組中,然後返回該元組作為結果。

以下是對上述方法的演示:

示例

 即時演示

from itertools import product

my_dict = {'month_num' : [1, 2, 3, 4, 5, 6], 'name_of_month' : ['Jan', 'Feb', 'March', 'Apr', 'May', 'June']}

print("The dictionary is : ")
print(my_dict)

my_result = dict(zip(my_dict['month_num'], my_dict['name_of_month']))

print("The flattened dictionary is: ")
print(my_result)

輸出

The dictionary is :
{'month_num': [1, 2, 3, 4, 5, 6], 'name_of_month': ['Jan', 'Feb', 'March', 'Apr', 'May', 'June']}
The flattened dictionary is:
{1: 'Jan', 2: 'Feb', 3: 'March', 4: 'Apr', 5: 'May', 6: 'June'}

說明

  • 將所需軟體包匯入到環境中。

  • 定義一個字典,並顯示在控制檯中。

  • 使用“zip”方法將字典的鍵和值繫結,然後再次轉換為字典。

  • 將其分配給一個變數。

  • 將其作為輸出顯示在控制檯中。

更新於:14-Apr-2021

519 次瀏覽

開啟你的 職業生涯

完成課程獲得認證

開始
廣告