如何在 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']}
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP