當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python dict()用法及代碼示例

Python dict() 函數是一個創建字典的構造函數。 Python 字典為創建字典提供了三種不同的構造函數。

  • 如果沒有傳遞參數,它會創建一個空字典。
  • 如果給出了位置參數,則會創建一個具有相同鍵值對的字典。否則,傳遞一個可迭代對象。
  • 如果給出了關鍵字參數,則關鍵字參數及其值將添加到從位置參數創建的字典中。

簽名

dict ([**kwargs])
dict ([mapping, **kwargs])
dict ([iterable, **kwargs])

參數

kwargs: 這是一個關鍵字參數。

mapping: 這是另一本字典。

iterable:它是一個鍵值對形式的可迭代對象。

返回

它返回一個字典。

讓我們看一些 dict() 函數的例子來理解它的函數。

Python dict() 函數示例 1

創建空或非空字典的簡單示例。字典的參數是可選的。

# Python dict() function example
# Calling function
result = dict() # returns an empty dictionary
result2 = dict(a=1,b=2)
# Displaying result
print(result)
print(result2)

輸出:

{}
{'a':1, 'b':2}

Python dict() 函數示例2

# Python dict() function example
# Calling function
result = dict({'x':5, 'y':10}, z=20) # Creating dictionary using mapping
result2 = dict({'x':5, 'y':10, 'z':20})
# Displaying result
print(result)
print(result2)

輸出:

{'x':5, 'z':20, 'y':10}
{'x':5, 'z':20, 'y':10}

Python dict() 函數示例3

# Python dict() function example
# Calling function
result = dict([(1, 'One'), [2, 'Two'], [3,'Three']]) # Creating using iterable
result2 = dict([['x','X'],('y','Y')])
# Displaying result
print(result)
print(result2)

輸出:

{1:'One', 2:'Two', 3:'Three'}
{'y':'Y', 'x':'X'}






相關用法


注:本文由純淨天空篩選整理自 Python dict() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。