【问题标题】:Concatenate string to list of dictionaries in python将字符串连接到python中的字典列表
【发布时间】:2025-12-27 12:35:17
【问题描述】:

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

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 错误的情况下将字符串连接到字典列表

【问题讨论】:

  • 您的预期结果是什么?字符串、字典还是元组?
  • 这个[site] + search_res?
  • 传递给join的参数项不能是字典;他们必须是字符串。这就是错误告诉你的。你想做什么?(很可能)为什么?

标签: python python-3.x list dictionary concatenation


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    也许你只需要这个: print(site + ' , ' + str(search_res))

    【讨论】:

      【解决方案3】:

      如何将字符串连接到字典列表

      你不能。你也不需要。使用string formatting,可能与the pprint module一起使用。

      【讨论】: