Python 字典列表

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

在本教程中,我们将学习如何在列表中创建字典,以及可以对其执行的操作。

那么,让我们开始在列表中创建一个字典。

考虑下面的程序,

输出

The dictionary inside list is:  [{'English': 31101, 'Hindi': 31102, 'Mathematics': 31103, 'Physics': 31104, 'Chemistry': 31105}]
The type of list_val is:  <class 'list'>
The dictionary inside second list is:  [{'Apples': 'Red', 'Bananas': 'Yellow', 'Lemons': 'Yellow', 'Peas': 'Green', 'Strawberries': 'Pink'}]
The type of slist_val is:  <class 'list'>

说明:

让我们来看一下上面程序的解释,

  1. 在第一步中,我们创建了一个列表,并在其中初始化了字典的元素。
  2. 然后我们显示了字典,并使用 type() 检查其类型,我们可以看到它是一个列表。
  3. 在此之后,我们在另一个列表中执行了相同的操作,其中字典的键值对是字符串形式的。

访问字典的值

现在,我们将看到如何访问字典的值,

下面的程序演示了如何做到这一点。

代码

输出

The dictionary inside list is:  [{'English': 31101}, {'Hindi': 31102}, {'Mathematics': 31103, 'Calculus': 311030}, {'Physics': 31104}, {'Chemistry': 31105}]
{'English': 31101}
31102
311030
The dictionary inside second list is:  [{'Apples': 'Red'}, {'Bananas': 'Yellow'}, {'Lemons': 'Yellow', 'Pineapple': 'Brown'}, {'Peas': 'Green'}, {'Strawberries': 'Pink'}]
{'Apples': 'Red'}
Yellow
Brown

说明:

让我们来理解一下我们在这里做了什么,

  1. 在第一步中,我们创建了一个列表,并在其中初始化了字典的元素。
  2. 然后我们使用索引访问了值,并进一步使用键获取了值。
  3. 在此之后,我们在另一个列表中执行了相同的操作,其中字典的键值对是字符串形式的。

更新字典的值

现在是时候学习如何更新字典的值了,

下面的程序说明了这一点,

输出

The dictionary inside list is:  [{'English': 31101}, {'Hindi': 31102}, {'Mathematics': 31103, 'Calculus': 311030}, {'Physics': 31104}, {'Chemistry': 31105}]
Updated dictionary is: [{'English': 31101}, {'Hindi': 41102}, {'Mathematics': 31103, 'Calculus': 311032}, {'Physics': 31104}, {'Chemistry': 31105}]
The dictionary inside second list is:  [{'Apples': 'Red'}, {'Bananas': 'Yellow'}, {'Lemons': 'Yellow', 'Pineapple': 'Brown'}, {'Peas': 'Green'}, {'Strawberries': 'Pink'}]
Updated dictionary is: [{'Apples': 'Red'}, {'Bananas': 'Green'}, {'Lemons': 'Yellow', 'Pineapple': 'Peach'}, {'Peas': 'Green'}, {'Strawberries': 'Pink'}]

说明:

让我们看看上面程序中到底发生了什么,

  1. 在第一步中,我们创建了一个列表,并在其中初始化了字典的元素。
  2. 然后我们使用索引更新了值,然后使用赋值运算符存储了新值。
  3. 在此之后,我们在另一个列表中执行了相同的操作,其中字典的键值对是字符串形式的。

追加字典的值

最后,我们将学习如何向字典中追加值。

考虑下面的程序,

输出

The dictionary inside list is:  [{'English': 31101}, {'Hindi': 31102}, {'Mathematics': 31103, 'Calculus': 311030}, {'Physics': 31104}, {'Chemistry': 31105}]
List after the appended values is:  [{'English': 31101}, {'Hindi': 31102}, {'Mathematics': 31103, 'Calculus': 311030}, {'Physics': 31104}, {'Chemistry': 31105}, {'Biology': 31106, 'Physical Training': 31107}]

说明:

现在是时候看看这个程序的解释了,

  1. 在第一步中,我们创建了一个列表,并在其中初始化了字典的元素。
  2. 然后我们使用 append() 方法追加了值,并指定了要添加的元素。

结论

在本教程中,我们学习了如何创建字典列表以及如何访问、更新和追加其中的值。