【发布时间】: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。