Python 如何创建一个空字典
字典是Python中的一种数据结构。字典也被称为 关联内存 或 关联数组 。它由 花括号 {} 表示。它以 键 和 值对 的形式存储数据。
与其他使用索引的数据结构不同,可以通过键来访问字典中的数据。要检索与特定键关联的值,必须使用索引值。由于字典中的键是唯一的,因此可以使用不可变对象(如元组或字符串)来标识它们。但是,存储在字典中的值不需要是唯一的。
可以通过两种方式创建空字典−
使用花括号 {}
在Python中创建一个空字典的一种方法是使用花括号 {}。为此,您只需将花括号对分配给变量,如下所示的语法−
语法
variable_name = {}
在此,
- variable_name 是字典的名称
-
{} 是用于创建空字典的符号
示例
在这个例子中,我们将大括号赋给变量,然后字典就被创建了。
dict1 = {}
print("The dictionary created using curly braces ",dict1)
print(type(dict1))
输出
当使用花括号创建空字典时,会得到以下输出。
The dictionary created using curly braces {}
<class 'dict'>
示例
在这里,我们尝试使用 {} 创建一个空字典,并将值附加到创建的空字典中。
dict1 = {}
print("The dictionary created using curly braces ",dict1)
dict1['a'] = 10
print("The dictionary after appending the key and value ",dict1)
print(type(dict1))
输出
下面是创建一个空字典并向其添加值的输出。我们可以看到,由于其数据类型提示,结果是一个空字典。
The dictionary created using curly braces {}
The dictionary after appending the key and value {'a': 10}
<class 'dict'>
使用dict()函数
我们还可以使用dict()函数创建字典。通常情况下,我们需要将键值对作为参数传递给该函数来创建字典。但是如果在不传递任何参数的情况下调用该函数,则会创建一个空字典。
语法
创建空字典的语法如下:
variable_name = dict()
其中,
- variable_name是字典的名称
-
dict是创建空字典的关键字
示例
以下是使用dict()函数创建空字典的示例-
dict1 = dict()
print("The dictionary created is: ",dict1)
print(type(dict1))
输出
The dictionary created is: {}
<class 'dict'>
示例
在这个例子中,我们首先创建一个空字典,并给它赋值 –
dict1 = dict()
print("Contents of the dictionary: ",dict1)
dict1['colors'] = ["Blue","Green","Red"]
print("Contents after inserting values: ",dict1)
输出
Contents of the dictionary: {}
Contents after inserting values: {'colors': ['Blue', 'Green', 'Red']}
示例
让我们看一个其他的例子 –
dict1 = dict()
print("Contents of the dictionary: ",dict1)
dict1['Language'] = ["Python","Java","C"]
dict1['Year'] = ['2000','2020','2001']
print("Contents after adding key-value pairs: ",dict1)
输出
Contents of the dictionary: {}
Contents after adding key-value pairs: {'Language': ['Python', 'Java', 'C'], 'Year': ['2000', '2020', '2001']}