Python 字典方法详解(python字典常用方法)


一、创建字典

1.1 花括号直接创建

创建空字典

student = {}

用键值对初始化

student = {

"name": "Alice",

"age": 20,

"courses": ["Math", "Physics"]

}

1.2 dict() 构造函数

创建空字典

person = dict()

传入键值对参数

person = dict(name="Bob", age=25, city="Shanghai")

# 注意字典构造函数中'键'不用字符串格式。如:name而非'name',这与上面大括号创建字典有所不同!

使用可迭代对象参数

pairs = [("a", 1), ("b", 2)]

d = dict(pairs)

print(d)

# 输出:{'a': 1, 'b': 2}

1.3 字典推导式

squares = {x: x**2 for x in range(5)}

print(squares)

# 输出:{0:0, 1:1, 2:4, 3:9, 4:16}

二、元素操作

2.1 访问元素

person = {'name': 'Alice', 'age': 25}

通过键访问

print(person['name'])

# 输出: Alice

使用get()方法,键不存在时返回None或默认值

print(person.get('age')) # 输出: 25

print(person.get('address')) # 输出: None

print(person.get('address', 'Not specified')) # 输出: Not specified

遍历所有值

for key in person:

print(key, person[key])

# 输出:

name Alice

age 25

2.2 添加/修改元素

student = {

"name": "Alice",

"age": 20,

"courses": ["Math", "Physics"]

}

student["phone"] = "138-1234-5678" # 新增

student["age"] = 21 # 修改

update() 合并字典

student.update({"grade": "A", "email": "alice@uni.edu"})

print(student)

# 输出:

{'name': 'Alice', 'age': 21, 'courses': ['Math', 'Physics'], 'phone': '138-1234-5678', 'grade': 'A', 'email': 'alice@uni.edu'}

2.3 删除元素

pop() 删除指定键(返回被删值)

deleted = student.pop("phone") # 138-1234-5678

popitem() 删除最后插入的键值对(Python3.7+ 按插入顺序)

last_item = student.popitem() # ('email', 'alice@uni.edu')

del 语句

del student["age"]

clear() 清空

student.clear()

三、常用方法详解

3.1 keys(), values(), items()

person = {'name': 'Alice', 'age': 25, 'city': 'New York'}

获取所有键

print(person.keys()) # dict_keys(['name', 'age', 'city'])

获取所有值

print(person.values()) # dict_values(['Alice', 25, 'New York'])

获取所有键值对

print(person.items()) # dict_items([('name', 'Alice'), ('age', 25), ('city', 'New York')])

#格式类似字符串元组的列表

items()通常与循环一起使用

for key, value in person.items():

print(f"{key}: {value}")

# 输出:

name: Alice

age: 25

city: New York

3.2 setdefault(key, default)

安全地设置默认值:

student.setdefault("major", "Computer Science")

# 如果键不存在则添加,返回默认值。键存在则返回当前值,不修改

3.3 copy()

浅拷贝:

new_dict = student.copy()

3.4 fromkeys(seq[, value])

创建新字典:从可迭代对象创建新字典,所有值设置为相同值

keys = ["name", "age", "city"]

default_dict = dict.fromkeys(keys, None)

# 输出:{'name': None, 'age': None, 'city': None}

3.5 合并字典(Python 3.9+)

d1 = {"a": 1}

d2 = {"b": 2}

merged = d1 | d2 # {'a':1, 'b':2}

# Same:

d1.update(d2)

print(d1) # {'a':1, 'b':2}

四、函数参数中的字典

4.1 作为参数传递

student = {"name": "Alice","age": 20,"courses": ["Math", "Physics"]}

def print_info(info):

for k, v in info.items():

print(f"{k}: {v}")

print_info(student)

# 输出:

name: Alice

age: 20

courses: ['Math', 'Physics']

4.2 可变参数 **kwargs

def create_profile(**kwargs):

return kwargs

profile = create_profile(name="Charlie", age=22, country="USA")

# 等同于 {'name': 'Charlie', 'age':22, 'country':'USA'}

4.3 参数解包

data = {"sep": "-", "end": "\n===\n"}

print("Hello", "world", **data)

# 输出:Hello-world

===

五、高级操作

5.1 字典推导式

过滤值大于2的键

original = {1: 10, 2: 20, 3: 30}

filtered = {k: v for k, v in original.items() if v > 15}

# 输出:{2: 20, 3: 30}

5.2 嵌套字典

nested = {

"user1": {"name": "Alice", "access": True},

"user2": {"name": "Bob", "access": False}

}

5.3 排序

num_dict = {x:9-x for x in range(9)}

# 按键排序

sorted_dict = dict(sorted(num_dict.items(), key=lambda x: x[0]))

# 按值排序

sorted_by_value = dict(sorted(num_dict.items(), key=lambda x: x[1]))

print(num_dict)

print(sorted_dict)

print(sorted_by_value)

# 输出:

{0: 9, 1: 8, 2: 7, 3: 6, 4: 5, 5: 4, 6: 3, 7: 2, 8: 1}

{0: 9, 1: 8, 2: 7, 3: 6, 4: 5, 5: 4, 6: 3, 7: 2, 8: 1}

{8: 1, 7: 2, 6: 3, 5: 4, 4: 5, 3: 6, 2: 7, 1: 8, 0: 9}

# dict.items()返回的是键值对,所以索引0代表键,索引1代表值.

六、注意事项

1. 键必须为不可变类型(字符串、数字、元组)

2. 值可以是任意Python对象

3. 字典3.7+版本保持插入顺序

4. 避免使用可变类型(如列表)作为键

5. 检查键是否存在时推荐使用 `key in dict`

这个总结涵盖了字典从创建到高级操作的完整流程,包含了函数参数传递的典型场景,以及版本特性说明。

当然,本文并没有把字典的方法全部列出,遗漏之处希望大家补充!

原文链接:,转发请注明来源!