Python dict() 函式



Python 的dict()函式用於建立一個新的字典。字典是一種資料結構,用於儲存鍵值對的集合。字典中的每個鍵都是唯一的,並對映到一個特定的值。它是一種可變(可更改)且無序的結構。

字典使用花括號{}定義,每個鍵值對用“冒號”分隔。例如,您可以使用字典來儲存姓名和對應的年齡等資訊。

語法

以下是 Python dict() 函式的語法:

dict(iterable)

引數

此函式接受一個元組列表作為引數,其中每個元組代表一個鍵值對。

返回值

此函式返回一個新的字典物件。

示例 1

在下面的示例中,我們使用帶有關鍵字引數的 dict() 函式來建立一個字典“person”,其中每個鍵都與一個特定值相關聯:

person = dict(name="Alice", age=30, city="New York")
print('The dictionary object obtained is:',person)

輸出

以下是上述程式碼的輸出:

The dictionary object obtained is: {'name': 'Alice', 'age': 30, 'city': 'New York'}

示例 2

在這裡,我們使用 dict() 函式將元組列表“data_tuples”轉換為字典,方法是將每個元組的第一個元素作為鍵,第二個元素作為值:

data_tuples = [("a", 1), ("b", 2), ("c", 3)]
data_dict = dict(data_tuples)
print('The dictionary object obtained is:',data_dict)

輸出

上述程式碼的輸出如下:

The dictionary object obtained is: {'a': 1, 'b': 2, 'c': 3}

示例 3

在這裡,我們結合使用 dict() 函式和列表推導式將“data_list”中的字典合併到一個字典中:

data_list = [{'name': 'Alice'}, {'age': 25}, {'city': 'London'}]
data_dict = dict((key, value) for d in data_list for key, value in d.items())
print('The dictionary object obtained is:',data_dict)

輸出

獲得的結果如下所示:

The dictionary object obtained is: {'name': 'Alice', 'age': 25, 'city': 'London'}

示例 4

在本例中,我們結合使用 dict() 函式和 zip() 函式將鍵和值列表中的元素配對以建立字典:

keys = ["name", "age", "city"]
values = ["Bob", 28, "Paris"]
person_dict = dict(zip(keys, values))
print('The dictionary object obtained is:',person_dict)

輸出

以下是上述程式碼的輸出:

The dictionary object obtained is: {'name': 'Bob', 'age': 28, 'city': 'Paris'}

示例 5

在這個例子中,我們首先使用 dict() 函式初始化一個空字典“empty_dict”。隨後,我們透過新增鍵值對來填充字典:

empty_dict = dict()
empty_dict["name"] = "John"
empty_dict["age"] = 30
empty_dict["city"] = "Berlin"
print('The dictionary object obtained is:',empty_dict)

輸出

產生的結果如下:

The dictionary object obtained is: {'name': 'John', 'age': 30, 'city': 'Berlin'}
python_type_casting.htm
廣告