dict() 函数用于创建字典。字典是一种可迭代的,数据以键值对的形式存储
示例:Student_dict = {
name :"Ram"
age : 22
course : "Bachelors"
}
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 函数,它也不会抛出错误。如果没有参数传递,它将返回一个空字典。
| 参数 | 描述 | 必需/可选 |
|---|---|---|
| **kwargs | 任意数量的关键字参数,形式为 key=value,用逗号分隔 逗号 |
必需 |
| 可迭代对象 | Python 中的任何可迭代对象 | 可选 |
| 映射 | 键到值的映射 | 可选 |
dict 函数的输出始终是一个字典。如果没有参数传递,则返回一个空字典
| 输入 | 返回值 |
|---|---|
| None | 空字典 |
| **kwargs | 将关键字参数转换为字典 |
| 可迭代对象 | 将可迭代对象转换为字典 |
| 映射 | 将映射转换为字典 |
letters = dict(a=1, b=2)
print(' Letters dictionary is', letters)
print(type(letters))
输出
Letters dictionary is {'a': 1, 'b': 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}
letters dictionay is {'a': 1, 'b': 2, 'c': 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}
letters dictionary is {'a': 1, 'b': 2, 'c': 3}