在JSON Python2.7中追加列表

2024-10-01 11:37:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我的JSON dict如下所示:

{
    "end": 1, 
    "results": [
        {
            "expired": false, 
            "tag": "search"
        }, 
        {
            "span": "text goes here"
        }
    ], 
    "totalResults": 1
}

这条生产线的产品是:

^{pr2}$

我的目标是让“span”键进入“results”列表。当totalResults>;1时,这是必需的。在

{
    "end": 1, 
    "results": [
        {
            "expired": false, 
            "tag": "search",
            "span": "text goes here"
        },
    ], 
    "totalResults": 1
}

我试过几种方法,比如用'dictname.update,但这会覆盖“results”中的现有数据。在


Tags: textjsonfalsesearchhere产品tagresults
2条回答

这里还有一个解决方案,如果你想你可以使用下面的代码。在

>>> tmp_response = {"end": 1,"results": [{"expired": False,"tag": "search"},{"span": "text goes here"}],"totalResults": 1}
>>> tmp_response['results'][0] = dict(tmp_response['results'][0].items() + {'New_entry': "Ney Value"}.items())
>>> tmp_response
{'totalResults': 1, 'end': 1, 'results': [{'tag': 'search', 'expired': False, 'New_entry': 'Ney Value'}, {'span': 'text goes here'}]}
>>> 
tmp_response['results'][0]['span'] = "text goes here"

或者,如果您真的想使用update

^{pr2}$

但请注意,这是一个不必要的创造

相关问题 更多 >