假设我们有以下配置字典:
config = {
"name": "Bob",
"age": 34,
"email": "bob@example.com"
}
我们可以使用for循环遍历字典并对其进行格式化,如下所示:
for key, value in config.items():
print("{}: {}".format(key, value))
这将输出以下内容:
name: Bob
age: 34
email: bob@example.com
我们可以根据需要自定义打印格式,例如使用制表符对齐:
for key, value in config.items():
print("{:<10} {}".format(key + ":", value))
这将输出以下内容:
name: Bob
age: 34
email: bob@example.com
此外,如果你想将字典转换为字符串,你可以使用字符串的join方法,如下所示:
output = "\n".join("{}: {}".format(key, value) for key, value in config.items())
print(output)
这将输出以下内容:
name: Bob
age: 34
email: bob@example.com