【问题标题】:Join array of objects to string value in Python在Python中将对象数组连接到字符串值
【发布时间】:2019-12-06 19:52:30
【问题描述】:

我想将对象数组连接到 python 中的字符串。我有什么办法可以做到吗?

url =  "https://google.com",
search = "thai food",
results = [
        {
            "restaurant": "Siam Palace",
            "rating": "4.5"
        },
        {
            "restaurant": "Bangkok Palace",
            "rating": "3.5"
        }
]

我希望能够将所有这些结合起来形成一个价值。

如果我可以让它看起来像:

 data = {    url =  "https://google.com", 
{
   search = "thai food",
   results = [
        {
            "restaurant": "Siam Palace",
            "rating": "4.5"
        },
        {
            "restaurant": "Bangkok Palace",
            "rating": "3.5"
        }
]
}
}

我正在从 mongodb 收到这些结果,并希望将这 3 个连接在一起。

【问题讨论】:

    标签: python arrays mongodb pymongo arrayobject


    【解决方案1】:

    使用 JSON 模块

    data = {} # create empty dict
    
    # set the fields
    data['url'] = 'https://google.com'
    data['search'] = 'thai food'
    
    # set the results
    data['results'] = results
    
    # export as string
    import json
    print(json.dumps(data, indent=4)
    

    【讨论】:

    • 谢谢。我能问你一个简单的问题吗?如何创建这些字典的数组?我有多个这样的价值观。我想要类似 data = {[],[]}
    • 你能帮我处理一下stackoverflow.com/questions/59260047/…吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-03
    • 2021-06-29
    • 1970-01-01
    • 1970-01-01
    • 2021-10-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多