Nee*_*ran 21 python string dictionary list object
我有一个字符串和一个对象列表:
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)
Run Code Online (Sandbox Code Playgroud)
我明白了:
TypeError: format requires a mapping
Run Code Online (Sandbox Code Playgroud)
我该如何打印?我正在尝试打印:
1 : big
2 : small
Run Code Online (Sandbox Code Playgroud)
谢谢
Pre*_*eti 17
由于格式化字符串使用命名参数:
gpl = "%(id)s : %(atr)s"
Run Code Online (Sandbox Code Playgroud)
您需要在字典中提供键(名称)作为参数,以引用格式化字符串中的命名格式化键:
print gpl % {'id': obj['id'], 'atr': con['atr']}
Run Code Online (Sandbox Code Playgroud)
所以你的代码是:
for obj in objects:
for con in obj['content']:
print gpl% {'id': obj['id'], 'atr': con['atr']}
Run Code Online (Sandbox Code Playgroud)