如何在Python中建立空字典?


字典是Python中的一種資料結構。字典也被稱為關聯記憶體關聯陣列。它用大括號{}表示,以鍵值對的形式儲存資料。

與使用索引的其他資料結構不同,字典中的資料可以透過其鍵訪問。要檢索與特定鍵關聯的值,必須使用鍵值。由於字典中的鍵是唯一的,因此任何不可變物件(如元組或字串)都可以用來標識它們。但是,儲存在字典中的值不必唯一。

建立空字典有兩種方法:

使用花括號{}

在Python中建立空字典的一種方法是使用花括號{}。為此,只需要將花括號對賦值給一個變數,如下面的語法所示:

語法

variable_name = {}

其中:

  • variable_name 是字典的名稱

  • {} 是建立空字典的符號

示例

在這個例子中,我們將花括號賦值給變數,然後建立字典。

dict1 = {}
print("The dictionary created using curly braces ",dict1)
print(type(dict1))

輸出

以下是使用花括號建立空字典時的輸出。

The dictionary created using curly braces {}
<class 'dict'>

示例

在這裡,我們嘗試使用{}建立一個空字典,並將值新增到已建立的空字典中。

dict1 = {}
print("The dictionary created using curly braces ",dict1)
dict1['a'] = 10
print("The dictionary after appending the key and value ",dict1)
print(type(dict1))

輸出

以下是建立空字典並向其中新增值的輸出。我們可以看到,結果結構是一個空字典,其資料型別表明了這一點。

The dictionary created using curly braces  {}
The dictionary after appending the key and value  {'a': 10}
<class 'dict'>

使用dict()函式

我們也可以使用dict()函式建立字典。通常,使用此函式建立字典需要將鍵值對作為引數傳遞給它。但是,如果我們呼叫此函式而不傳遞任何引數,則會建立一個空字典。

語法

以下是建立空字典的語法。

variable_name = dict()

其中:

  • variable_name 是字典的名稱

  • dict是建立空字典的關鍵字

示例

以下是用dict()函式建立空字典的示例:

dict1 = dict()
print("The dictionary created is: ",dict1)
print(type(dict1))

輸出

The dictionary created is:  {}
<class 'dict'>

示例

在這個例子中,我們首先建立一個空字典,然後為其賦值。

dict1 = dict()
print("Contents of the dictionary: ",dict1)
dict1['colors'] = ["Blue","Green","Red"]
print("Contents after inserting values: ",dict1)

輸出

Contents of the dictionary:  {}
Contents after inserting values:  {'colors': ['Blue', 'Green', 'Red']}

示例

讓我們看另一個例子:

dict1 = dict()
print("Contents of the dictionary: ",dict1)
dict1['Language'] = ["Python","Java","C"]
dict1['Year'] = ['2000','2020','2001']
print("Contents after adding key-value pairs: ",dict1)

輸出

Contents of the dictionary:  {}
Contents after adding key-value pairs:  {'Language': ['Python', 'Java', 'C'], 'Year': ['2000', '2020', '2001']}

更新於:2023年5月15日

3K+ 次瀏覽

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.