Python 字典输出问题如何解决?

有一个字典 d = {‘a’:“1”,‘b’:“2”,“c”:3} 有连个变量 foo=‘test1’ bar=‘test2’ 如何格式化输出成下面的格式?

# str 是固定的字符
str,id=test1,ip=test2 a=1 b =2 c=3
Python 字典输出问题如何解决?

4 回复

’ ‘.join(str(i[0])+’=’+str(i[1]) for i in d.items())


帖子没给具体报错或代码,我猜你可能是遇到了字典打印不美观、乱码或者想按特定格式输出。直接上几个常见情况的代码和解释。

1. 如果你只是想让打印好看点(比如JSON格式):

import json
my_dict = {'name': '张三', 'age': 25, 'skills': ['Python', 'Java']}
print(json.dumps(my_dict, indent=2, ensure_ascii=False))

indent=2 让输出有缩进,ensure_ascii=False 保证中文正常显示。

2. 如果你想遍历输出键值对:

my_dict = {'a': 1, 'b': 2}
for key, value in my_dict.items():
    print(f'{key}: {value}')

3. 如果你在输出时遇到 TypeError: unhashable type 错误: 这通常是因为你用了列表等可变类型作为字典的键。改法:

# 错误示例
# bad_dict = {['key']: 'value'}  # 列表不能当键

# 正确:用元组或字符串
good_dict = {('key',): 'value'}  # 元组不可变,可以当键
print(good_dict)

4. 如果你需要排序输出:

my_dict = {'c': 3, 'a': 1, 'b': 2}
for key in sorted(my_dict.keys()):
    print(key, my_dict[key])

总结:先明确具体问题,对症下药。

其实你这个关键就是怎么把字典中的值按格式 print()出来把? python3 有个新的 format 方式,叫 f=string,比较好理解:
也就是在 一个"string"前面加一个 f,然后用花括号来带入格式
a = 123
b = 456
print(f"the value of a is {a}, the value of b is {b}")
# >>> the value of a is 123, the value of b is 456

同理
d = {‘a’:“1”,‘b’:“2”,“c”:3}
print(f"a={d[‘a’]} b={d[‘b’]} c={d[‘c’]}")
合并于你的其他要求就是:
print(f"string, id={foo} ip={bar} a={d[‘a’]} b={d[‘b’]} c={d[‘c’]}")

打错了,是 f-string

回到顶部