【问题标题】:How to use list update/insert key/value json object in python如何在python中使用列表更新/插入键/值json对象
【发布时间】:2016-02-22 04:56:09
【问题描述】:

我正在尝试将多个 json 对象更新/插入到列表字典中。示例:插入 "state": "Kuala Kuala Lumpur" of "City": "Kuala lumpur" 和 "state": "Melaka" of "City": "Kuala sungai巴鲁”。这是我的代码:

    import json
    j=[{"City": "Kuala lumpur",
    "Population (2000)": "1410300",
    "Latitude (DD)": "3.160",
    "Longitude (DD)": "101.710", 
    },
    {
            "City": "Kuala sungai baru",
            "Population (2000)": "11700",
            "Latitude (DD)": "2.350",
            "Longitude (DD)": "102.030"
    }]
    # how to update for key/value multiple json obj
    # how to insert for all json obj
    iter(j).next()['nation'] = u'malaysia' 
    #load json
    data= json.dumps(j)
    json_str= json.loads(data)
    #get key
    keys =[item['nation'] for item in json_str] # KeyError: ('nation',)

【问题讨论】:

  • Key error 出现是因为您只有一个文档中有nation
  • Python 中没有 json 对象 这样的东西。有dict

标签: python json


【解决方案1】:

这一行

iter(j).next()['nation'] = u'malaysia'

仅更新结构中的第一个条目。

试试:

for it in j:
    it['nation'] = u'malaysia'

【讨论】:

    猜你喜欢
    • 2019-12-11
    • 1970-01-01
    • 2021-07-12
    • 1970-01-01
    • 2021-09-27
    • 2021-02-06
    • 1970-01-01
    • 1970-01-01
    • 2019-12-04
    相关资源
    最近更新 更多