Python dict() 函数用于创建 Python 字典。字典是键值对的集合。字典是一种可变数据结构,即可以修改字典中的数据。在 python 3.6 和更早版本中,字典是键值对的无序集合,但从 python 3.7 开始,字典是有序数据结构。字典是一种索引数据结构,即可以使用索引来访问字典的内容,这里在字典中键用作索引。
范例1:使用关键字参数创建字典
我们可以将关键字参数作为参数传递,其中所需的值将是字典的键和值。
用法:
class dict(**kwarg)
Python3
# passing keyword arguments to dict() method
myDict = dict(a=1, b=2, c=3, d=4)
print(myDict)
输出:
{'a':1, 'b':2, 'c':3, 'd':4}
例子2:通过映射键和值来创建字典
键也可以使用冒号映射到值,多个键值对可以用逗号分隔并传递给 dict()。
用法:
class dict(mapping, **kwarg)
Python3
# passing key-values pairs mapped by colon to dict function
myDict = dict({'a':1, 'b':2, 'c':3})
print(myDict)
输出:
{'a':1, 'b':2, 'c':3}
范例3:使用可迭代创建字典
键和值可以以列表或元组等可迭代的形式传递给 dict() 以形成字典,关键字参数也可以传递给 dict()。
用法:
class dict(iterable, **kwarg)
Python3
# A list of key value pairs is passesd and
# keyword argument is also passed
myDict = dict([('a', 1), ('b', 2), ('c', 3)], d=4)
print(myDict)
输出:
{'a':1, 'b':2, 'c':3, 'd':4}
相关用法
- Python dict.items()和dict.iteritems()的区别用法及代码示例
- Python enchant.Dict()用法及代码示例
- Python Wand function()用法及代码示例
注:本文由纯净天空筛选整理自mohan1240760大神的英文原创作品 Python dict() Function。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。