【问题标题】:Appending a list inside of a JSON - Python 2.7在 JSON 中附加一个列表 - Python 2.7
【发布时间】:2013-11-11 10:13:54
【问题描述】:

我的 JSON 字典如下所示:

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

这是这条线的产品:

tmp_response['results'].append({'span':"text goes here"})

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

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

我尝试了几种方法,例如使用“dictname.update”,但这会覆盖“结果”中的现有数据。

【问题讨论】:

  • 您要更新第一个结果还是所有结果?

标签: python json list python-2.7 dictionary


【解决方案1】:
tmp_response['results'][0]['span'] = "text goes here"

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

tmp_response['results'][0].update({'span':"text goes here"})

但请注意,这是不必要的字典创建。

【讨论】:

  • 还有另一种选择:.update(span='text goes here') 与后一种选择...
  • 唯一需要做的改变当然是用实际的列表计数器更新 [0] 元素。
【解决方案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去这里'}]} >>>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-28
    • 1970-01-01
    • 1970-01-01
    • 2015-02-08
    相关资源
    最近更新 更多