Python dict() 函数用于创建新字典。字典是一种存储键值对集合的数据结构。字典中的每个键都是唯一的,并映射到特定值。它是一个可变 (可变) 和无序的结构。
词典使用大括号 {} 定义,每个键值对用 “冒号” 分隔。例如,您可以使用字典来存储姓名和相应年龄等信息。
语法
以下是 Python dict() 函数的语法 -
dict(iterable)
参数
此函数接受元组列表作为参数,其中每个元组表示一个键值对。
返回值
此函数返回一个新的字典对象。
示例 1在下面的示例中,我们将使用带有关键字参数的 dict() 函数来创建一个字典 “person”,其中每个键都与特定值相关联 -
person = dict(name="Alice", age=30, city="New York")
print('The dictionary object obtained is:',person)
输出
以下是上述代码的输出 -
The dictionary object obtained is: {'name': 'Alice', 'age': 30, 'city': 'New York'}
示例 2
在这里,我们使用 dict() 函数将元组列表 “data_tuples” 转换为字典,方法是将每个元组的第一个元素关联为键,将第二个元素关联为值 -
data_tuples = [("a", 1), ("b", 2), ("c", 3)]
data_dict = dict(data_tuples)
print('The dictionary object obtained is:',data_dict)
输出
上述代码的输出如下 -
The dictionary object obtained is: {'a': 1, 'b': 2, 'c': 3}
示例 3
在这里,我们使用 dict() 函数和列表推导式将 “data_list” 中的字典合并为一个字典 -
data_list = [{'name': 'Alice'}, {'age': 25}, {'city': 'London'}]
data_dict = dict((key, value) for d in data_list for key, value in d.items())
print('The dictionary object obtained is:',data_dict)
输出
获得的结果如下所示 -
The dictionary object obtained is: {'name': 'Alice', 'age': 25, 'city': 'London'}
示例 4
在这种情况下,我们将 dict() 函数与 zip() 函数结合使用,将键和值列表中的元素配对以创建字典 -
keys = ["name", "age", "city"]
values = ["Bob", 28, "Paris"]
person_dict = dict(zip(keys, values))
print('The dictionary object obtained is:',person_dict)
输出
以下是上述代码的输出 -
The dictionary object obtained is: {'name': 'Bob', 'age': 28, 'city': 'Paris'}
示例 5
在此示例中,我们首先使用 dict() 函数初始化一个空字典 “empty_dict”。随后,我们通过添加键值对来填充字典 -
empty_dict = dict()
empty_dict["name"] = "John"
empty_dict["age"] = 30
empty_dict["city"] = "Berlin"
print('The dictionary object obtained is:',empty_dict)
输出
生成的结果如下 -
The dictionary object obtained is: {'name': 'John', 'age': 30, 'city': 'Berlin'}