Python 比较两个字典中的键并使用for循环更新值
具有点要素的GeoJson包含两个属性:城市和评级。 城市作为标识从未改变,但评级将定期更新。 新评级作为vales(“dnew”)存储在字典中。 我的for循环工作不正常。请参阅下面的代码,其中“#问题在这里”标记了我无法解决的问题Python 比较两个字典中的键并使用for循环更新值,python,json,python-3.x,dictionary,geojson,Python,Json,Python 3.x,Dictionary,Geojson,具有点要素的GeoJson包含两个属性:城市和评级。 城市作为标识从未改变,但评级将定期更新。 新评级作为vales(“dnew”)存储在字典中。 我的for循环工作不正常。请参阅下面的代码,其中“#问题在这里”标记了我无法解决的问题 import json dnew = {"Budapest": "fair", "New York": "very good", "Rome": "awesome"} data = { "type": "FeatureCollection", "name":
import json
dnew = {"Budapest": "fair", "New York": "very good", "Rome": "awesome"}
data = {
"type": "FeatureCollection",
"name": "Cities",
"crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:OGC:1.3:CRS84" } },
"features": [
{ "type": "Feature", "properties": { "City": "New York", "Rating": "good" }, "geometry": { "type": "Point", "coordinates": [ -73.991836734693834, 40.736734693877537 ] } },
{ "type": "Feature", "properties": { "City": "Rome", "Rating": "fair" }, "geometry": { "type": "Point", "coordinates": [ 12.494557823129199, 41.903401360544223 ] } },
{ "type": "Feature", "properties": { "City": "Budapest", "Rating": "awesome" }, "geometry": { "type": "Point", "coordinates": [ 19.091836734693832, 47.494557823129256 ] } }
]
}
#at this point, keys of two dictionaies are compared. If they are the same, the value of the old dict is updated/replaced by the value of the new dict
for key in data["features"]:
citykey = (key["properties"]["City"])
ratingvalue = (key["properties"]["Rating"])
#print(citykey + "| " + ratingvalue)
for keynew in dnew:
citynew = (keynew)
ratingnew = dnew[keynew]
#print(citynew + " | " + ratingnew)
print(citykey + "==" + citynew)
if citykey == citynew:
#
#here is the problem
#
data["features"]["properties"]["Rating"] = ratingnew
print(True)
else:
print(False)
错误消息:
TypeError: list indices must be integers or slices, not str
谢谢大家! 由于它是一个列表而不是一个字典,所以它遗漏了“features”后面的数字索引
data[“features”][0][“properties”][“Rating”]
对于data[“features”]
列表中的每个元素,在dnew
字典中循环所有键,这样就失去了字典的好处
E.Coms注意到您遇到的问题,但只检查列表中的第一项(数据[“功能”][0]
)
也许以下几点可以解决你的问题
for key in data["features"]:
citykey = (key["properties"]["City"])
ratingvalue = (key["properties"]["Rating"])
#print(citykey + "| " + ratingvalue)
if citykey in dnew:
key["properties"]["Rating"] = dnew[citykey]