一、什么是Python字典?Python字典是一种内置的数据类型,它由键值对组成,可以存储任意类型的数据。字典中的键是唯一的,而值可以是任意类型,包括其他字典。这使得字典在处理复杂数据结构和映射关系时...
Python字典是一种内置的数据类型,它由键值对组成,可以存储任意类型的数据。字典中的键是唯一的,而值可以是任意类型,包括其他字典。这使得字典在处理复杂数据结构和映射关系时非常有用。
在Python中,你可以使用花括号{}来创建一个空字典,或者使用dict()函数来创建一个字典。
# 使用花括号创建字典
empty_dict = {}
# 使用dict()函数创建字典
student_info = dict(name="Alice", age=20, major="Computer Science")你可以通过键来访问字典中的值。如果键不存在,会引发KeyError。
print(student_info["name"]) # 输出:Alice为了避免KeyError,可以使用get()方法。
print(student_info.get("name")) # 输出:Alice
print(student_info.get("phone")) # 输出:None你可以直接通过键来修改字典中的值。
student_info["age"] = 21你可以直接使用赋值操作来添加新的键值对。
student_info["phone"] = "1234567890"你可以使用del语句来删除键值对。
del student_info["phone"]或者使用pop()方法。
student_info.pop("name")for key in student_info.keys(): print(key)for value in student_info.values(): print(value)for key, value in student_info.items(): print(key, value)获取所有键的列表。
keys_list = list(student_info.keys())获取所有值的列表。
values_list = list(student_info.values())获取所有键值对的列表。
items_list = list(student_info.items())更新字典。
new_info = {"city": "New York", "country": "USA"}
student_info.update(new_info)student_info.clear()text = "Hello, World!"
char_count = {}
for char in text: if char in char_count: char_count[char] += 1 else: char_count[char] = 1
print(char_count)users = { "Alice": {"age": 20, "major": "Computer Science"}, "Bob": {"age": 22, "major": "Mathematics"}
}
print(users["Alice"]["age"]) # 输出:20dictionary = { "hello": "你好", "world": "世界"
}
print(dictionary["hello"]) # 输出:你好Python字典是一种非常强大且灵活的数据结构,它能够高效地存储和检索数据。通过本文的介绍,你应该已经掌握了创建、访问、修改和遍历字典的基本技巧。在实际应用中,字典可以帮助你处理各种复杂的数据结构和映射关系,提高编程效率。