dict()
函數用於創建字典。字典是一個可重複的表,其中數據以鍵和值對的形式存儲
示例:Student_dict = {
名稱:「Ram」
年齡:22
課程:「單身漢」
dict()
函數可以通過三種不同的方式使用
僅繞過關鍵字參數
**dict(**kwargs)** #where kwargs denotes keyword arguments of form key=value
繞過可迭代參數和關鍵字參數
**dict(iterable,**kwargs)** #where iterable can be any iterable like a list
通過傳遞映射和關鍵字參數
**dict(mapping,**kwargs)** #where mapping is key to value pair mapping
dict()
參數:
即使沒有參數傳遞給 dict 函數,它也不會拋出錯誤。如果沒有傳遞參數,它將返回一個空字典。
參數 | 描述 | 必需/可選 |
---|---|---|
**誇格斯 | 任意數量的關鍵字參數,形式為 key =由 | |
逗號分隔的值 | 需要 | |
可迭代的 | python 中的任何可迭代函數 | 可選擇的 |
繪圖 | 鍵到值對映射 | 可選擇的 |
dict()
返回值
dict 函數的輸出總是字典。如果沒有傳遞參數,將返回一個空字典
| 投入 | 返回值 |
| 沒有人 | 空字典 |
| **誇格斯 | 將關鍵字參數轉換為字典 |
| 可重複的 | 將可條目轉換為字典 |
| 繪圖 | 將映射轉換為字典 |
Python 中dict()
方法的示例
示例 1:僅傳遞關鍵字參數
letters = dict(a=1, b=2)
print(' Letters dictionary is', letters)
print(type(letters))
輸出:
Letters dictionary is {'a': 1, 'b': 2}
<class></class>
示例 2:傳遞數據項
# iterable without keyword arguments
letters = dict((a,1), (b=2))
print(' letters dictionary is', letters)
print(type(letters))
# iterable with keyword arguments
letters = dict([('a',1), ('b',2)],c=3)
print(' letters dictionay is', letters)
print(type(letters))
輸出:
letters dictionay is {'a': 1, 'b': 2}
<class>letters dictionay is {'a': 1, 'b': 2, 'c': 3}
<class></class></class>
示例 3:傳遞映射
# Mapping without keyword arguments
letters = dict({『a』 : 1,』b』:2})
print(' letters dictionary is', letters)
print(type(letters))
# Mapping with keyword arguments
letters = dict({『a』 : 1,』b』:2},c=3)
print(' letters dictionary is', letters)
print(type(letters))
輸出:
letters dictionary is {'a': 1, 'b': 2}
<class>letters dictionary is {'a': 1, 'b': 2, 'c': 3}
<class></class></class>
原創文章,作者:簡單一點,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/127433.html