Python 中的嵌套字典

在 Python 編程語言中,我們有字典的概念。字典是可變的,我們可以輕鬆地在字典中添加和刪除條目。它是無序數據項的集合。

  • 字典由兩部分組成,第一部分是數據集,第二部分是其對應的鍵值。
  • 它也不允許重複。
  • 這裡的嵌套字典是指字典內部的字典。
  • 簡單來說就是指字典,由一套多本字典組成。
  • 用於存儲鍵值對中的數據值。
  • 嵌套字典意味着將一個字典放在另一個字典中。嵌套非常有用,因為我們可以在程序中建模的信息種類大大擴展了。
  • 嵌套字典包含各種字典的無序集合。
  • 與普通字典相比,它還包含鍵及其值對。
  • 我們可以用它的鑰匙查字典。
  • 通過將逗號分隔的字典放在大括號內,可以在 Python 中創建嵌套字典。
  • 切片嵌套字典是不可能的。
  • 我們可以根據需要縮小或擴大嵌套字典。

用於將各種字典添加到特定字典中的嵌套字典語法:

向嵌套字典添加元素可以通過多種方式完成。在嵌套字典中添加字典的一種方法是添加一對一的值,嵌套字典[dict][key] = ‘value ‘。另一種方法是一次性添加整個字典,nested dict[dict]= { ‘ key ‘:’ value ‘ }。

嵌套字典示例

讓我們藉助一些例子來理解:

例 1:


# Let us first create a normal dictionary that contains data items with their 
# corresponding key-value pairs in a python programming language.
# It contains an integer key with the corresponding string values
dict = {1: 'Rina', 2: 'Gita', 3: 'Sita'}
print("\n Printing the dictionary that contains integer keys with their corresponding values")
print(dict)

說明:

在上面的例子中,我們創建了一個包含整數鍵值和相應字符串值的字典。這裡我們用班級中的學生數據進行了符號化,每個學生的名字對應一個學號。此外,我們將在這個字典中執行嵌套操作。

以下程序的輸出

Printing the dictionary that contains integer keys with their corresponding values
{1: 'Rina', 2: 'Gita', 3: 'Sita'}

例 2:


# In the example we will create a simple empty dictionary using python 
# programming language
dict = {}
print("Simple empty Dictionary: ")
print(dict)

說明:

我們已經創建了一個不包含任何具有相應值的鍵的字典。此外,我們將在這個字典中執行嵌套操作。

以下程序的輸出

Simple empty dictionary:
{ }

例 3:


# Python program to print Empty nested dictionary
dict = { 'dict1': { },                              # Nested dictionary syntax
        'dict2': { }, 'dict3': { }}
print("Nested dictionary are as follows -")
print(dict)

說明:

我們創建了一個嵌套字典,它包含空的數據集,或者一個空字典,它不包含任何帶有相應鍵值的數據項。

以下程序的輸出

Nested dictionary are as follows -
{'dict1': {}, 'dict2': {}, 'dict3': {}}

例 4:


# Let us first create a normal dictionary that contains data items with their 
# corresponding key value pairs in python programming language.
# It contains string key with the corresponding key values
dict = {'A': 1, 'B': 2, 'C': 3, 'D':4, 'E':5}
print("\n Printing the dictionary that contains string keys with their corresponding integer values")
print(dict)

說明:

在上面的例子中,我們創建了一個包含字符串鍵值和相應整數值的字典。這裡我們用學生的數據符號化了有年級的班級中每個學生對應的學號。此外,我們將在這個字典中執行嵌套操作。

以下程序的輸出

Printing the dictionary that contains string keys with their corresponding integer values
{'A': 1, 'B': 2, 'C': 3, 'D': 4, 'E': 5}

例 5:


# Let us first create a normal dictionary that contains data items with their 
# corresponding key-value pairs in a python programming language.
# Here, each item has formed a pair 
Dict = dict([(1, 'silk'), (2, 'one')])
print("\nDictionary with each item as a pair: ")
print(Dict)

說明:

我們創建了一個包含成對數據項的字典。我們已經創建了一個配對項目的列表,並將其作為字典。

以下程序的輸出

Dictionary with each item as a pair: 
{1: 'silk', 2: 'one'}

例 6:


# Let us first create a dictionary that contains data items with their corresponding 
# key value pairs, and here we would assign the values to the keys separately in 
# Python programming language.

Dict={}
Dict[1] = 'Java'
Dict[2] = 'Tpoint'
Dict[3] = 1
print("\nDictionary after adding 3 elements: ")
print(Dict)

說明:

我們已經創建了三個獨立的字典,並在相應的鍵值處逐一分配了元素。該字典包含整數鍵值和相應的字符串值。儘管如此,我們還是單獨創建了它,之後,我們添加了這些字典。因此,我們可以在字典中執行加法運算。我們還將在這個字典中執行嵌套操作。

以下程序的輸出

Dictionary after adding 3 elements: 
{1: 'Java', 2: 'Tpoint', 3: 1}

例 7:


# Let us first create a dictionary that contains data items with their corresponding 
# key value pairs in a python programming language.
# Here, we would perform the addition and update operation in the nested dictionary
# to a single Key
Dict['Value'] = 5, 3, 6
print("\nDictionary after adding 3 elements: ")
print(Dict)

# Updating existing Key's Value
Dict[2] = 'JavaTpoint'
print("\nUpdated key value: ")
print(Dict)

# Adding Nested Key value to Dictionary
Dict[5] = {'Nested' :{'5' : 'Java', '3' : 'T'}}
print("\n Adding a Nested Key: ")
print(Dict)

說明:

我們創建了一個字典,其中包含整數鍵值和相應的字符串值。這裡,我們已經在字典中執行了更新和添加操作。我們還對它進行了一些修改,並將其轉換為嵌套字典。

以下程序的輸出

Dictionary after adding 3 elements: 
{'Name': 'JavaTpoint', 1: [11, 12, 13], 'Value': (5, 3, 6)}
Updated key value: 
{'Name': 'JavaTpoint', 1: [11, 12, 13], 'Value': (5, 3, 6), 2: 'JavaTpoint'}
Adding a Nested Key: 
{'Name': 'JavaTpoint', 1: [11, 12, 13], 'Value': (5, 3, 6), 2: 'JavaTpoint', 5: {'Nested': {'5': 'Java', '3': 'T'}}}

例 8:


# Let us first create a nested dictionary that contains data items with their 
# corresponding key-value pairs in a python programming language.
# Nested dictionary having the mixed keys 
Dict = {'Name': 'JavaTpoint', 1: [11, 12, 13]}
print("\nDictionary with the use of Mixed Keys: ")
print(Dict)

說明:

我們已經創建了一個嵌套字典,其中包含了鍵值和相應的值。在這裡,我們使用了混合鍵的概念,其中鍵是不一樣的。我們將擴展它,並使用相同的鍵但不同的值創建一個嵌套字典。

以下程序的輸出

Dictionary with the use of Mixed Keys: 
{'Name': 'JavaTpoint', 1: [11, 12, 13]}

例 9:


# Let us first create a nested dictionary that contains data items with their 
# corresponding key-value pairs in a python programming language.
# Nested dictionary having the same keys 
Dict = { 'Dict1': {'Name': 'Reena', 'age': '22'},
        'Dict2': {'Name': 'Jatin', 'age': '19'}}
print("\n Nested dictionary 2-")
print(Dict)

說明:

在上面的例子中,我們創建了一個嵌套的字典,其中包含了鍵值和對應的值,這裡我們使用了相同鍵的概念,其中鍵是相同的,但是對應的數據值是不同的。

以下程序的輸出

Nested dictionary 2-
{'Dict1': {'Name': 'Reena', 'age': '22'}, 'Dict2': {'Name': 'Jatin', 'age': '19'}}

例 10:


# Let us first create a nested dictionary that contains data items with their 
# corresponding key-value pairs in a python programming language.
# Nested dictionary having the mixed keys 
Dict = { 'Dict1': {1: 'J', 2: 'T', 3: 'P'},
        'Dict2': {'Name': 'JTP', 1: [1, 2]} }
print("\n Nested dictionary 3-")
print(Dict)
Dict3 = { }
print("Initial nested dictionary:-")
print(Dict3)

Dict3['Dict1'] = {}

# Adding elements one at a time
Dict3['Dict1']['name'] = 'Boby'
Dict3['Dict1']['age'] = 21
print("\n After adding dictionary Dict1")
print(Dict3)

說明:

我們已經創建了一個嵌套字典,其中包含整數鍵值和相應的字符串值。在這裡,我們首先打印了嵌套字典和一個空的嵌套字典。我們做了一些更改,將嵌套字典放在空字典中。我們還添加了兩個嵌套字典。

以下程序的輸出

Nested dictionary 3-
{'Dict1': {1: 'J', 2: 'T', 3: 'P'}, 'Dict2': {'Name': 'JTP', 1: [1, 2]}}
Initial nested dictionary:-
{}
After adding dictionary Dict1
{'Dict1': {'name': 'Boby', 'age': 21}}

讓我們舉一個固定的例子,然後看看其中的一些變化,這樣我們就可以很容易很容易地理解:

例 11:


# creating a nested dictionary named as student
student = {1: {'name': 'Shivam', 'age': '22', 'Id': 10023},
          2: {'name': 'Anjali', 'age': '20', 'Id': 10024}}

print(student)

說明:

這裡我們創建了一個簡單的嵌套字典;此外,我們將做出一些改變。

以下程序的輸出

{1: {'name': 'Shivam', 'age': '22', 'Id': 10023}, 2: {'name': 'Anjali', 'age': '20', 'Id': 10024}}

例 12:


# creating a nested dictionary named as student and accesing the elements using [] syntax
student = {1: {'name': 'Shivam', 'age': '22', 'Id': 10023},
          2: {'name': 'Anjali', 'age': '20', 'Id': 10024}}

print(student[1]['name'])
print(student[1]['age'])
print(student[1]['Id'])

說明:

在這裡,我們創建了一個嵌套字典,並使用[ ]語法從字典中訪問元素,在這裡,當我們在您想要獲取的元素的這個[ ]方括號位置提供字典的名稱,然後在附加[ ]方括號中提供您想要為特定元素獲取的屬性或鍵值時,使用它。

以下程序的輸出

Shivam
22
10023

例 13:


# creating a nested dictionary named as student and here we are adding one more 
# element in the dictionary
student = {1: {'name': 'Shivam', 'age': '22', 'Id': 10053},
          2: {'name': 'Anjali', 'age': '20', 'Id': 10004}}

student[3] = {}

student[3]['name'] = 'Tina'
student[3]['age'] = '19'
student[3]['Id'] = '10034'

print(student[3])

說明:

在這裡,我們已經創建了一個嵌套的字典,我們希望向該字典中添加更多的元素。這一切都是通過使用[ ]方括號語法來完成的,首先我們在字典中的位置 3 創建了一個空集合,然後我們一個接一個地向其中填充數據,在這裡當我們提供字典的名稱時使用它,然後在您想要添加的元素的這個[ ]方括號位置和附加[ ]方括號中的 than 之後,使用等號來提供您想要為特定元素分配的屬性或鍵值。

以下程序的輸出

{'name': 'Tina', 'age': '19', 'Id': '10034'}

例 14:


# creating a nested dictionary named as student and here we are adding one more  
# element in the dictionary, after than we want to perform delete operation into it 
# for deleting particular elements from a particular dictionary indide the nested 
# dictionary.
student = {1: {'name': 'Shivam', 'age': '22', 'Id': 10053},
          2: {'name': 'Anjali', 'age': '20', 'Id': 10004}}

student[3] = {}

student[3]['name'] = 'Tina'
student[3]['age'] = '19'
student[3]['Id'] = '10034'

print(student[3])
del student[3][ 'Id']
print(student[3])

說明:

在這裡,我們已經創建了一個嵌套的字典,我們希望向該字典中添加更多的元素。這都是通過使用[ ]方括號語法完成的。首先,我們在字典中的位置 3 創建了一個空集合,然後我們一個接一個地將數據填入其中。

在這裡,當我們提供字典的名稱,然後在您想要添加的元素的這個[ ]方括號位置,然後在附加的[ ]方括號中提供您想要使用等於符號為特定元素分配的屬性或鍵值時,使用它。

現在刪除特定的元素,比如說從嵌套字典中刪除學生 3 的 id;我們必須在其中使用『del』關鍵字;通過使用它,我們可以很容易地刪除我們想要的特定值。

以下程序的輸出

{'name': 'Tina', 'age': '19', 'Id': '10034'}
{'name': 'Tina', 'age': '19'}

例 15:


# creating a nested dictionary named as student and here we are adding one more  
# element in the dictionary, after than we want to perform delete operation into it 
# for deleting particular elements from a particular dictionary inside the nested 
# dictionary.
student = {1: {'name': 'Shivam', 'age': '22', 'Id': 10053},
          2: {'name': 'Anjali', 'age': '20', 'Id': 10004}}

student[3] = {}

student[3]['name'] = 'Tina'
student[3]['age'] = '19'
student[3]['Id'] = '10034'

print(student[3])
del student[3]
print(student)

說明:

在這裡,我們已經創建了一個嵌套的字典,我們希望向該字典中添加更多的元素。這都是通過使用[ ]方括號語法完成的。首先,我們在字典中的位置 3 創建了一個空集合,然後我們一個接一個地將數據填充到其中,在這裡,當我們提供字典的名稱時使用它,然後在您想要添加的元素的這個[ ]方括號位置中,然後在附加的[ ]方括號中提供您想要使用等號為特定元素分配的屬性或鍵值。

為了刪除嵌套字典中的特定字典,我們使用了’ del ‘關鍵字,並從學生嵌套字典中刪除了學生 3 的整個字典。

以下程序的輸出

{'name': 'Tina', 'age': '19', 'Id': '10034'}
{1: {'name': 'Shivam', 'age': '22', 'Id': 10053}, 2: {'name': 'Anjali', 'age': '20', 'Id': 10004}}

原創文章,作者:PLMIO,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/316306.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
PLMIO的頭像PLMIO
上一篇 2025-01-09 12:14
下一篇 2025-01-09 12:14

相關推薦

  • Python中引入上一級目錄中函數

    Python中經常需要調用其他文件夾中的模塊或函數,其中一個常見的操作是引入上一級目錄中的函數。在此,我們將從多個角度詳細解釋如何在Python中引入上一級目錄的函數。 一、加入環…

    編程 2025-04-29
  • 如何查看Anaconda中Python路徑

    對Anaconda中Python路徑即conda環境的查看進行詳細的闡述。 一、使用命令行查看 1、在Windows系統中,可以使用命令提示符(cmd)或者Anaconda Pro…

    編程 2025-04-29
  • Python列表中負數的個數

    Python列表是一個有序的集合,可以存儲多個不同類型的元素。而負數是指小於0的整數。在Python列表中,我們想要找到負數的個數,可以通過以下幾個方面進行實現。 一、使用循環遍歷…

    編程 2025-04-29
  • Python計算陽曆日期對應周幾

    本文介紹如何通過Python計算任意陽曆日期對應周幾。 一、獲取日期 獲取日期可以通過Python內置的模塊datetime實現,示例代碼如下: from datetime imp…

    編程 2025-04-29
  • Python周杰倫代碼用法介紹

    本文將從多個方面對Python周杰倫代碼進行詳細的闡述。 一、代碼介紹 from urllib.request import urlopen from bs4 import Bea…

    編程 2025-04-29
  • python強行終止程序快捷鍵

    本文將從多個方面對python強行終止程序快捷鍵進行詳細闡述,並提供相應代碼示例。 一、Ctrl+C快捷鍵 Ctrl+C快捷鍵是在終端中經常用來強行終止運行的程序。當你在終端中運行…

    編程 2025-04-29
  • 蝴蝶優化算法Python版

    蝴蝶優化算法是一種基於仿生學的優化算法,模仿自然界中的蝴蝶進行搜索。它可以應用於多個領域的優化問題,包括數學優化、工程問題、機器學習等。本文將從多個方面對蝴蝶優化算法Python版…

    編程 2025-04-29
  • Python程序需要編譯才能執行

    Python 被廣泛應用於數據分析、人工智能、科學計算等領域,它的靈活性和簡單易學的性質使得越來越多的人喜歡使用 Python 進行編程。然而,在 Python 中程序執行的方式不…

    編程 2025-04-29
  • Python字典去重複工具

    使用Python語言編寫字典去重複工具,可幫助用戶快速去重複。 一、字典去重複工具的需求 在使用Python編寫程序時,我們經常需要處理數據文件,其中包含了大量的重複數據。為了方便…

    編程 2025-04-29
  • Python清華鏡像下載

    Python清華鏡像是一個高質量的Python開發資源鏡像站,提供了Python及其相關的開發工具、框架和文檔的下載服務。本文將從以下幾個方面對Python清華鏡像下載進行詳細的闡…

    編程 2025-04-29

發表回復

登錄後才能評論