# Python字典使用指南：基本操作与方法

**URL:** <https://www.isharkfly.com/t/python/17101>\
**Category:** 程序语言\
**Tags:** python\
**Created:** [March 20, 2025, 6:40pm UTC](https://www.isharkfly.com/t/python/17101 "2025-03-20T18:40:09Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![honeymoose](https://www.isharkfly.com/user_avatar/www.isharkfly.com/honeymoose/32/20796_2.png) [@honeymoose](https://www.isharkfly.com/u/honeymoose)\
**Post date:** [March 20, 2025, 6:40pm UTC](https://www.isharkfly.com/t/python/17101/1 "2025-03-20T18:40:09Z")

</div>

Python dict 如何使用

---

<div class="post-metadata">

**Author:** ![hex](https://www.isharkfly.com/user_avatar/www.isharkfly.com/hex/32/21953_2.png) [@hex](https://www.isharkfly.com/u/hex)\
**Post date:** [March 20, 2025, 6:40pm UTC](https://www.isharkfly.com/t/python/17101/2 "2025-03-20T18:40:10Z")

</div>

# Python dict 使用指南

Python中的字典(dict)是一种可变的、无序的键值对集合。以下是如何使用Python字典的基本操作：

## 创建字典

```python
# 空字典
my_dict = {}
# 或者
my_dict = dict()

# 带初始值的字典
person = {"name": "张三", "age": 30, "city": "北京"}

```

## 访问元素

```python
# 通过键访问值
name = person["name"] # 返回 "张三"

# 使用get方法(推荐，当键不存在时不会报错)
age = person.get("age") # 返回 30
hobby = person.get("hobby") # 键不存在，返回 None
hobby = person.get("hobby", "读书") # 键不存在，返回默认值 "读书"

```

## 添加或修改元素

```python
# 添加新键值对
person["hobby"] = "编程"

# 修改已有键的值
person["age"] = 31

```

## 删除元素

```python
# 使用del删除
del person["city"]

# 使用pop方法删除并返回值
age = person.pop("age") # 删除age键并返回其值

# 清空字典
person.clear()

```

## 常用方法

```python
# 获取所有键
keys = person.keys()

# 获取所有值
values = person.values()

# 获取所有键值对
items = person.items() # 返回(key, value)元组的列表

# 检查键是否存在
if "name" in person:
    print("Name exists")

# 合并两个字典
dict1 = {"a": 1, "b": 2}
dict2 = {"b": 3, "c": 4}
dict1.update(dict2) # dict1现在是 {"a": 1, "b": 3, "c": 4}

# 复制字典
dict_copy = person.copy()

```

## 字典推导式

```python
# 创建平方数字典
squares = {x: x*x for x in range(6)} # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

```

## 注意事项

1. 字典键必须是不可变类型(如字符串、数字、元组，但不能是列表)
2. 字典是无序的(Python 3.7+保证了插入顺序)
3. 键是唯一的，重复键会覆盖前一个键值对

希望这个指南对你使用Python字典有所帮助！

 ![Dictionary-in-Python-1024x742](https://cdn.isharkfly.com/com-isharkfly-www/discourse-uploads/original/3X/8/b/8bd6db7901d980e559019dd11467664c27291070.png)  
与其他语言的对比来看，有点像 Java 语言中的 map。

---

<div class="post-metadata">

**Author:** ![honeymoose](https://www.isharkfly.com/user_avatar/www.isharkfly.com/honeymoose/32/20796_2.png) [@honeymoose](https://www.isharkfly.com/u/honeymoose)\
**Post date:** [March 20, 2025, 6:40pm UTC](https://www.isharkfly.com/t/python/17101/3 "2025-03-20T18:40:56Z")

</div>

Made this topic public on March 20, 2025, 6:40pm UTC


