如何在 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']}

更新于: 2023年5月15日

3K+ 浏览量

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.