首页 > 解决方案 > 将字符串连接到python中的字典列表

问题描述

我正在尝试将字符串加入字典列表。我在做:

print(site + ', '.join(search_res))

我不断收到错误消息:sequence item 0: expected str instance, dict found

search_res = [
    {
        "book": "Harry Potter",
        "rating": "10.0"
    },
    {
        "book": "Lord of The Rings",
        "rating": "9.0"
    }
]

site = "Fantasy"

预期结果:

"Fantasy" , [
    {
        "book": "Harry Potter",
        "rating": "10.0"
    },
    {
        "book": "Lord of The Rings",
        "rating": "9.0"
    }
]

如何将字符串连接到字典列表而不会出现sequence item 0: expected str instance, dict found错误

标签: pythonpython-3.xlistdictionaryconcatenation

解决方案


为什么不只是print(site + str(search_res))

你也可以这样做:print(site + ', '.join([str(dic) for dic in search_res)])


推荐阅读