使用 Python 中給定的列表建立巢狀字典


Python 字典是靈活的資料結構,可以有效地儲存鍵值對。巢狀字典是一種分層資料結構,用於組織和管理大量資料。本文展示瞭如何從給定的列表構建巢狀字典,使字典使用者能夠執行各種任務。

語法

巢狀多層字典以適應複雜的資料結構。

nested_dict = { 'outer_key': { 'inner_key': 'value' } }

演算法

1. 建立一個新的字典來包含分層結構。

2. 迭代地遍歷給定的列表。

3. 提取列表中每個專案所需的鍵和值資訊。

4. 驗證巢狀字典以檢視外部鍵是否存在。

5. 如果存在,請檢視該外部鍵的內部鍵是否存在。

6. 否則,新增或更改值。

7. 如果缺少外部鍵,則使用指定的鍵值對構建一個新的內部字典,並將其新增到巢狀字典中。

示例

employee_list = [
   (101, 'John', 30, 'HR'),
   (102, 'Jane', 28, 'Engineering'),
   (103, 'Mike', 32, 'Finance')
]

employee_data = {}

for employee in employee_list:
   employee_id, name, age, department = employee
   if department in employee_data:
      employee_data[department][employee_id] = {'name': name, 'age': age}
   else:
      employee_data[department] = {employee_id: {'name': name, 'age': age}}

問題陳述是:使用員工資料建立巢狀字典。這應該將員工資料分組為表示員工 ID、姓名、年齡和部門的元組。

建立一個名為 employee data 的空字典。透過迴圈遍歷員工列表來儲存員工 ID、姓名、年齡和部門等資訊。如果部門作為外部鍵存在於 employee data 中,則更新員工資訊。如果不存在,則使用鍵員工 ID 構建一個新的內部字典,並存儲員工資料。

其他示例

1. 假設他們有一個學生在不同學科中成績的列表。根據他們的成績或表現,使用基於層次結構的資料結構來組織這些資料。

2. 有多個商品在不同地區的銷售資料。根據產品類別和位置,使用分層字典將此資料轉換為結構化形式。

當然!下面的程式碼示例演示了生成和操作複雜巢狀字典的方法。

帶使用者輸入的巢狀字典

nested_dict = {}

num_employees = int(input("Total headcount? :"))

for i in range(num_employees):
   employee_id = int(input(f"Enter Employee {i+1} ID: "))
   name = input(f"Enter Employee {i+1} Name: ")
   age = int(input(f"Employee {i+1} Age: "))
   department = input(f"Employee {i+1} Department: ")

   if department in nested_dict:
      nested_dict[department][employee_id] = {'name': name, 'age': age}
   else:
      nested_dict[department] = {employee_id: {'name': name, 'age': age}}

print("Nested Dictionary:", nested_dict)

使用 defaultdict 的巢狀字典

from collections import defaultdict

employee_list = [
   (101, 'John', 30, 'HR'),
   (102, 'Jane', 28, 'Engineering'),
   (103, 'Mike', 32, 'Finance'),
   (104, 'Alice', 25, 'Engineering'),
]

employee_data = defaultdict(dict)

for employee in employee_list:
   employee_id, name, age, department = employee
   employee_data[department][employee_id] = {'name': name, 'age': age}

print("Nested Dictionary using defaultdict:", dict(employee_data))

合併兩個巢狀字典

sales_data1 = {
   'ProductA': {'Region1': 100, 'Region2': 200},
   'ProductB': {'Region1': 150, 'Region3': 300},
}

sales_data2 = {
   'ProductA': {'Region2': 250, 'Region4': 180},
   'ProductC': {'Region1': 120, 'Region3': 80},
}

merged_sales_data = {}

for product, region_data in sales_data1.items():
   merged_sales_data[product] = region_data.copy()

for product, region_data in sales_data2.items():
   if product in merged_sales_data:
      merged_sales_data[product].update(region_data)
   else:
      merged_sales_data[product] = region_data

print("Merged Sales Data:", merged_sales_data)

訪問巢狀字典中的值

student_grades = {
   'John': {'Math': 90, 'Science': 85, 'History': 78},
   'Jane': {'Math': 95, 'English': 88, 'Science': 92},
}

jane_science_grade = student_grades['Jane']['Science']
print("Jane's Science Grade:", jane_science_grade)

john_history_grade = student_grades.get('John', {}).get('History', 'Not available')
print("John's History Grade:", john_history_grade)

應用

  • 對分層資料結構的處理示例包括建模組織層次結構、檔案系統或配置。

  • 管理複雜資料,例如巢狀 JSON 物件、圖形或多維資料集。

  • 描述事物之間的連線,例如依賴關係或父子關係。

  • 有效遍歷、探索或排序分層資料結構的演算法。

結論

本文說明了如何使用列表在 Python 中構建巢狀字典。詳細討論了安裝、語法和演算法。巢狀字典是處理和組織資料的有效工具。列表使訪問和修改資料結構的特定部分變得簡單,從而提高了 Python 程式的實用性和效率。

更新於: 2023年8月9日

883 次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始
廣告