如何格式化打印字典信息?出现'dict' object has no attribute 'format'报错
问题分析与解决办法
首先,先说说你遇到的AttributeError的原因:你把format方法用错对象啦!format是字符串专属的方法,而你写的{}.format(...)里,那个{}会被Python当成一个空字典,字典根本没有format这个方法,所以才会报错'dict' object has no attribute 'format'。
接下来咱们一步步实现你要的输出效果:
步骤1:配对grades和attendance的元素
要让两个列表的元素一一对应交替输出,首先得把它们每一组配对起来,Python的zip()函数刚好能做这件事——它会把两个列表中位置相同的元素打包成元组,比如('True', 100)、('True', 80)这样。
步骤2:展开配对后的元素
配对后我们得到的是一个个元组,需要把这些元组里的元素全部展开成一个扁平的序列,这样才能按True 100 True 80...的顺序排列。
步骤3:拼接成目标字符串输出
最后把名字和展开后的元素用空格连接起来,输出即可。
完整代码示例
kayleigh = {'name':'Kayleigh', 'grades':[100,80,67,100,89], 'attendance':['True','True','True','True','True']} # 用zip配对两个列表,再通过列表推导式展开所有元素 combined_items = [item for pair in zip(kayleigh['attendance'], kayleigh['grades']) for item in pair] # 用f-string拼接输出,简洁直观 print(f"Kayleigh: {' '.join(combined_items)}")
运行结果
Kayleigh: True 100 True 80 True 67 True 100 True 89
如果你习惯用format方法来写,也可以换成这种写法:
print("Kayleigh: {}".format(' '.join(combined_items)))
这样就完全符合你的需求啦~
内容的提问来源于stack exchange,提问作者WY G
相关产品推荐
相关产品推荐

