python - 类型错误 : Format Requires Mapping

标签 python string list object dictionary

我有一个字符串和一个对象列表:

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/

相关文章:

python - 平均列表python列

python - 如何在 PyCharm 中制作部分

asp.net - 如何以编程方式测量 ASP.NET 中的字符串像素宽度?

css - 内置函数不适用于评估的字符串,为什么?

python - 如何将字符串 append 到字典中的列表

c++ - O(1) std 或 boost 列表连接

python - 从字典或列表创建 pandas 数据帧太慢,有什么建议吗?

python - 如何使用正确的大小写获取 python 脚本的路径?

Java - 字符串和数组引用

python - 在Python中的for循环中嵌套列表