我有一个字符串和一个对象列表:
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
我将如何打印这个?我正在尝试打印:
1 : big
2 : small
谢谢
最佳答案
由于您的格式化字符串使用命名参数:
gpl = "%(id)s : %(atr)s"
您需要提供字典中的键(名称)作为参数来引用格式化字符串中命名的格式化键:
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']}
关于python - 类型错误 : Format Requires Mapping,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9990177/