首頁  >  文章  >  後端開發  >  Python - 從字典中取得特定的嵌套層級項

Python - 從字典中取得特定的嵌套層級項

PHPz
PHPz轉載
2023-08-20 14:37:13779瀏覽

Python - 从字典中获取特定的嵌套级别项

在Python中,字典允許您儲存鍵值對,從而輕鬆地組織和有效率地存取資料。有時,我們可能需要從字典的嵌套層級中檢索特定的項目。我們可以使用isinstance()與遞歸方法和dict.get()方法從字典中取得巢狀層級的項目。在本文中,我們將探討從Python字典中取得特定嵌套層級項的不同方法。

巢狀字典

嵌套字典是一個包含其他字典作為值的字典。這允許創建層次結構,其中資料以樹狀方式組織。層次結構的每個層級表示一個鍵值對,值是另一個字典。從這樣的結構中存取項目需要透過樹的層級進行導航的特定方法。

方法1:使用遞迴

By using the recursive method, we can easily retrieve items from nested levels within a dictionary without explicitly specifying each level. It provides a flexible and efficient solution, especially each level. It provides a flexible and efficient solution, especiallyen dealing with allycomplex#.

演算法

  • 定義一個函數,我們稱為get_nested_item,它接受兩個參數:字典資料和表示嵌套層級的鍵列表。

  • 檢查鍵列表是否為空。如果是空的,則傳回數據,因為它表示所需嵌套層級的值。

  • 否則,從鍵列表中取得第一個鍵

  • 檢查資料字典中是否存在該鍵。如果存在,則使用與該鍵對應的值作為新的資料參數以及鍵列表中剩餘的鍵,遞歸呼叫get_nested_item函數。

  • 如果鍵不存在,則傳回None或預設值來表示未找到該項目。

Example

的中文翻譯為:

範例

在下面的範例中,我們定義了

get_nested_item函數,該函數接受資料字典和鍵列表作為參數。我們檢查鍵列表是否為空;如果是,則傳回資料值。否則,我們從鍵列表中取得第一個鍵,並檢查它是否存在於資料字典中。如果存在,我們以對應的值作為新資料和鍵列表中剩餘的鍵,遞歸呼叫get_nested_item函數。如果找不到鍵,則傳回None。

def get_nested_item(data, keys):
    if len(keys) == 0:
        return data

    key = keys[0]
    if key in data:
        return get_nested_item(data[key], keys[1:])
    else:
        return None

keys = ['employees', 'John', 'position']
position = get_nested_item(company_data, keys)
print(position)

輸出

Manager

方法2:使用isinstance()和遞迴

isinstance()函數在Python中用來檢查物件的類型。如果物件是指定類型的實例,則傳回True,否則傳回False。我們可以將此函數與遞歸一起使用,動態地遍歷巢狀字典的層級。

演算法

  • 定義一個函數,我們稱為get_nested_item,它接受兩個參數:字典資料和表示嵌套層級的鍵列表。

  • 檢查鍵列表是否為空。如果是空的,則傳回數據,因為它表示所需嵌套層級的值。

  • 否則,從鍵列表中取得第一個鍵。

  • 使用 isinstance(data, dict) 檢查資料是否為字典。如果是,使用對應鍵的值作為新的資料參數,並將剩餘的鍵列表作為參數遞歸呼叫 get_nested_item 函數。

  • 如果資料不是一個字典或鍵不存在,則傳回None或預設值來表示該項目未找到。

Example

的中文翻譯為:

範例

在下面的範例中,我們使用

isinstance(data, dict) 來檢查資料是否為字典。如果是,我們繼續遞歸呼叫 get_nested_item。這個檢查確保我們在導航有效的字典層級時避免遇到存取不存在的鍵時出現錯誤。

def get_nested_item(data, keys):
    if len(keys) == 0:
        return data

    key = keys[0]
    if isinstance(data, dict) and key in data:
        return get_nested_item(data[key], keys[1:])
    else:
        return None

keys = ['employees', 'John', 'position']
position = get_nested_item(company_data, keys)
print(position)

輸出

Manager

Method 3: Using dict.get() method

dict.get()方法是從字典中檢索值並在找不到鍵時提供預設值的有用方式。與直接使用字典索引相比,特別是在處理巢狀字典或不知道鍵是否存在時,它是一種更簡潔和安全的方法。

Example

的中文翻譯為:

範例

In the below example, we have a nested dictionary

company_data representing employee information. We use company_data.get('employees', {}).get('John', {}) .get('position', 'Unknown') to retrieve the position of employee 'John'. By using dict.get() at each level, we ensure that the code easily handles missing keys without raising an error. Inan error. In case any key is missing, the default value 'Unknown' is returned.

company_data = {
    'employees': {
        'John': {
            'age': 30,
            'position': 'Manager',
            'department': 'Sales'
        },
        'Emily': {
            'age': 25,
            'position': 'Developer',
            'department': 'IT'
        }
    }
}
position = company_data.get('employees', {}).get('John', {}).get('position', 'Unknown')
print(position)

輸出

Manager

結論

在本文中,我們討論如何使用遞歸、isinstance和遞歸方法以及使用dict.get()方法從字典中取得特定的巢狀層級項目。當你對一個鍵的存在不確定或想要輕鬆處理缺少的鍵時,dict.get()方法特別有用。 isinstance()函數和遞歸使我們能夠有效率地遍歷巢狀的字典。

以上是Python - 從字典中取得特定的嵌套層級項的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除