插件窝 干货文章 Python 中如何对字典数据进行格式化输出与对齐

Python 中如何对字典数据进行格式化输出与对齐

输出 使用 格式化 对齐 225    来源:    2025-03-14

在 Python 中,可以使用多种方法对字典数据进行格式化输出和对齐。以下是几种常见的方法:

1. 使用 str.format() 方法

str.format() 方法可以用于格式化字符串,并且可以通过指定宽度和对齐方式来对齐输出。

data = {
    'name': 'Alice',
    'age': 30,
    'city': 'New York'
}

# 使用 str.format() 进行格式化输出
for key, value in data.items():
    print("{:<10} {:<10}".format(key, value))

输出:

name       Alice     
age        30        
city       New York  
  • {:<10} 表示左对齐,并且字段宽度为 10 个字符。
  • {:>10} 表示右对齐。
  • {:^10} 表示居中对齐。

2. 使用 f-string(Python 3.6+)

f-string 是 Python 3.6 引入的一种更简洁的字符串格式化方法。

data = {
    'name': 'Alice',
    'age': 30,
    'city': 'New York'
}

# 使用 f-string 进行格式化输出
for key, value in data.items():
    print(f"{key:<10} {value:<10}")

输出:

name       Alice     
age        30        
city       New York  

3. 使用 pprint 模块

pprint 模块可以用于“漂亮打印”数据结构,特别是对于嵌套的字典和列表。

import pprint

data = {
    'name': 'Alice',
    'age': 30,
    'city': 'New York'
}

# 使用 pprint 进行格式化输出
pprint.pprint(data, width=20)

输出:

{'age': 30,
 'city': 'New York',
 'name': 'Alice'}

4. 使用 tabulate

tabulate 是一个第三方库,可以用于生成漂亮的表格输出。

from tabulate import tabulate

data = {
    'name': 'Alice',
    'age': 30,
    'city': 'New York'
}

# 使用 tabulate 进行格式化输出
print(tabulate(data.items(), headers=["Key", "Value"], tablefmt="pretty"))

输出:

+------+----------+
| Key  |  Value   |
+------+----------+
| name | Alice    |
| age  | 30       |
| city | New York |
+------+----------+

5. 使用 json 模块

如果你想要以 JSON 格式输出字典数据,可以使用 json 模块。

import json

data = {
    'name': 'Alice',
    'age': 30,
    'city': 'New York'
}

# 使用 json 进行格式化输出
print(json.dumps(data, indent=4))

输出:

{
    "name": "Alice",
    "age": 30,
    "city": "New York"
}

总结

  • 对于简单的对齐需求,可以使用 str.format()f-string
  • 对于复杂的嵌套结构,可以使用 pprintjson 模块。
  • 如果需要生成表格形式的输出,可以使用 tabulate 库。

根据你的具体需求选择合适的方法。