Python 字典 type() 方法



Python 字典 type() 方法用於檢索傳遞的變數的型別。如果傳遞的變數是字典,則它將返回字典型別。

字典是 Python 中的一種對映資料型別。由鍵及其對應值組成的集合構成的資料型別稱為對映型別。對映是可變物件,這意味著在建立之後可以修改其狀態。

語法

以下是Python 字典 type() 方法的語法:

type(dict)

引數

  • dict - 這是字典。

返回值

此方法返回傳遞的變數的型別。

示例

以下示例顯示了 Python 字典 type() 方法的使用。這裡建立了一個字典 'dict'。然後使用 type() 方法檢索字典中傳遞的變數的型別。

# creating a dictionary
dict = {'Name': 'Zara', 'Age': 7};
# printing the result
print ("Variable Type : %s" %  type (dict))

當我們執行以上程式時,它會產生以下結果:

Variable Type : <class 'dict'>

示例

在這裡,我們正在建立一個空字典 'dict_1'。然後使用 type() 方法返回空字典的型別。

# Creating an empty dictionary
dict_1 = {};
res = type(dict_1)
# Printing the result
print ("The equivalent string is: ", res)

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

The equivalent string is:  <class 'dict'>

示例

在下面的示例中,我們建立了一個巢狀字典 'dict_1' 的列表。然後使用 type() 方法返回此字典的型別。

dict_1 = [{'Universe' : {'Planet' : 'Earth'}}]
print("The dictionary is: ", dict_1)
# using type() method
result = type(dict_1)
print("The equivalent string is: ", result)

上述程式碼的輸出如下:-

The dictionary is:  [{'Universe': {'Planet': 'Earth'}}]
The equivalent string is:  <class 'list'>
python_dictionary.htm
廣告