类型错误:格式需要映射 [英] Type Error: Format Requires Mapping
本文介绍了类型错误:格式需要映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个字符串和一个对象列表:
I have a string and a list of objects:
gpl = "%(id)s : %(atr)s"
objects = [{'id':1, 'content':[{'atr':'big', 'no':2}]}, {'id':2, 'content': [{'atr':'small', 'no':3}]}]
for obj in objects:
for con in obj['content']:
print gpl %(obj,con)
我得到:
TypeError: format requires a mapping
我该如何打印?我正在尝试打印:
How would I print this? I am trying to print:
1 : big
2 : small
谢谢
推荐答案
由于格式字符串使用命名参数:
Since your formatting string uses named parameters:
gpl = "%(id)s : %(atr)s"
您需要在字典中提供键(名称)作为自变量,以引用格式字符串中的命名格式键:
You need to provide keys (the names) in a dictionary as an argument to reference back to named formatting keys in the formatting string:
print gpl % {'id': obj['id'], 'atr': con['atr']}
因此您的代码应为:
for obj in objects:
for con in obj['content']:
print gpl% {'id': obj['id'], 'atr': con['atr']}
这篇关于类型错误:格式需要映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文