Python入门教程(十五)Python的字典

  • Post category:Python

Python中的字典是另一种内置的数据结构,它允许我们存储键值对。相比其他的数据结构,字典有着更快的访问速度,且可以通过键来快速找到值。在本文中,我们将详细介绍Python字典的使用。

字典的创建

下面是创建字典的基本语法:

{
  "key1": "value1",
  "key2": "value2",
  "key3": "value3"
}

注意,在字典中,键必须是唯一的,而且必须是不可改变的数据类型,比如字符串,数字或元组。

字典的访问

字典中的值可以通过对应的键来访问,例如:

fruits = {"apple": "red", "banana": "yellow", "orange": "orange"}
print(fruits["apple"])  # 输出 "red"

如果访问不存在的键会抛出KeyError异常。如果不确定某个键是否存在,可以使用in运算符来检查:

fruits = {"apple": "red", "banana": "yellow", "orange": "orange"}
if "apple" in fruits:
    print(fruits["apple"])  # 输出 "red"
else:
    print("Apple not found")

字典的修改和添加

可以使用键来修改字典中的值,例如:

fruits = {"apple": "red", "banana": "yellow", "orange": "orange"}
fruits["banana"] = "green"
print(fruits)  # 输出 {'apple': 'red', 'banana': 'green', 'orange': 'orange'}

如果键不存在,则会添加一个新的键值对:

fruits = {"apple": "red", "banana": "yellow", "orange": "orange"}
fruits["grape"] = "purple"
print(fruits)  # 输出 {'apple': 'red', 'banana': 'yellow', 'orange': 'orange', 'grape': 'purple'}

字典的删除

可以使用del关键字删除字典中的一个键值对或整个字典。

fruits = {"apple": "red", "banana": "yellow", "orange": "orange"}
del fruits["apple"]  # 删除键为"apple"的键值对
print(fruits)  # 输出 {'banana': 'yellow', 'orange': 'orange'}

del fruits  # 删除整个字典

字典的遍历

可以使用for循环遍历字典中的所有键值对:

fruits = {"apple": "red", "banana": "yellow", "orange": "orange"}

for key, value in fruits.items():
    print(key, value)

这将输出:

apple red
banana yellow
orange orange

示例1

下面是一个简单的演示,演示了如何使用字典来计算某个字符串中每个字符出现的次数:

s = "hello world"
counts = {}
for c in s:
    if c in counts:
        counts[c] += 1
    else:
        counts[c] = 1

for key, value in counts.items():
    print(key, value)

输出结果为:

h 1
e 1
l 3
o 2
  1
w 1
r 1
d 1

示例2

下面是另一个示例,演示了如何通过字典来计算某个数组中每个元素出现的次数:

nums = [1, 2, 3, 1, 2, 1, 4]
counts = {}
for n in nums:
    if n in counts:
        counts[n] += 1
    else:
        counts[n] = 1

for key, value in counts.items():
    print(key, value)

输出结果为:

1 3
2 2
3 1
4 1

以上就是Python字典的基本用法。希望这篇文章能为初学者提供一些帮助。