如何在 Python 中创建字典

2024 年 8 月 29 日 | 5 分钟阅读

在 Python 中,字典是一种无序的数据条目序列,可以用来记录数据条目,就像地图一样。与只能将单个项作为对象的其他数据结构不同,字典包含键值对。字典包含一个键值字段,以提高此数据类型的效率。

创建字典

我们可以通过将一组对象用大括号括起来并用逗号分隔来在 Python 中创建字典。字典会跟踪一对条目,其中一部分称为键,另一部分称为键的值,并称为键值对。我们可以将任何数据类型存储为键的值,并将相同的值赋予两个键,但键应该是不可变的且唯一的。

代码

输出

Dictionary created using curly braces: 
{1: 'Javatpoint', 2: 'Python', 3: 'Dictionary'}

Dictionary with keys of multiple data type: 
{'Website': 'Javatpoint', 3: [2, 3, 5, 'Dictionary']}

内置的 dict() 方法也可以用来生成字典。只需放置两个大括号 {} 就可以创建一个空字典。

代码

输出

An empty Dictionary: 
{}

Dictionary created by using dict() method: 
{1: 'Python', 2: 'Javatpoint', 3: 'Dictionary'}

Dictionary with key:value pair format: 
{1: 'Javatpoint', 2: 'Python', 3: 'Dictionary'}

向字典添加元素

可以使用多种方法在 Python 字典中插入项。可以使用此特定格式 Dictionary[Key] = 'Value' 将项添加到字典中。我们可以使用内置的 update() 函数来更新字典中现有的键。嵌套的键值对也可以插入到预先存在的字典中。如果键值对已存在于字典中,则会修改该键的值;如果不存在,则会创建一个新键并将其添加到字典中,值为给定值。

代码

输出

The empty Dictionary: 
{}

Dictionary after addition of these elements: 
{0: 'Javatpoint', 2: 'Python', 3: 'Dictionary'}

Dictionary after addition of the list: 
{0: 'Javatpoint', 2: 'Python', 3: 'Dictionary', 'list_values': (3, 4, 6)}

Updated dictionary: 
{1: 'Javatpoint', 2: 'Python'}

After addtion of a Nested Key: 
{0: 'Javatpoint', 2: 'Tutorial', 3: 'Dictionary', 'list_values': (3, 4, 6), 5: {'Nested_key': {1: 'Nested', 2: 'Key'}}}

从字典中移除元素

使用 pop() 函数,我们可以从字典中删除特定项。此函数返回已删除键的值。

popitem() 函数会移除并返回给定字典中的任意(键,值)元素对。我们可以使用 clear() 函数一次性删除所有对象。

我们也可以使用 del 关键字来删除单个项甚至整个字典。

代码

输出

After removing a key using pop(): 
{1: 'a', 2: 'b', 3: 'c', 5: 'e'}

After removing an arbitrary key: 
{1: 'a', 2: 'b', 3: 'c'}

After removing all the items: 
{}
No dictionary of the given name

Python字典方法

我们可以与字典一起使用的技术如下。其中一些在本教程中已经提到过。

方法描述
clear()删除字典中的所有项。
copy()返回字典的浅拷贝。
fromkeys(seq[, v])此函数生成一个新字典,其键为 seq,值为 v(键的默认值为 None)。
get(key[,d])此函数返回特定键的值。如果键不存在,则返回 d。
items()它以(键,值)格式返回一个包含字典内容的新对象。
keys()创建一个包含字典键的新对象。
pop(key[,d])删除与给定键关联的项并返回其值,如果找不到键,则返回 d。如果未指定 d 且在字典中未找到给定键,则会引发 KeyError。
popitem()删除并返回一个随机的(键,值)对象。如果给定字典为空,则会引发 KeyError。
setdefault(key[,d])如果字典中存在该键,则返回关联的值。如果不存在,则返回 d 并将该键与值 d 添加进去。(默认值为 None)。
update([other])覆盖给定字典中已存在的键
values()使用字典的元素初始化一个新字典对象。