比较两个字典中的键并使用for循环更新值

时间:2018-11-03 16:55:53

标签: python json python-3.x dictionary geojson

具有点要素的GeoJson包含两个属性:城市评分城市作为标识符永远不会更改,但是评级将定期更新。 新的 Rating 作为值(“ dnew”)存储在字典中。 我的for循环运行不正常。请查看下面的代码,其中“ #here是问题”表示我无法解决的问题。

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

谢谢!

2 个答案:

答案 0 :(得分:1)

由于它是列表而不是字典,因此在“功能”之后遗漏了数字索引。

data["features"][0]["properties"]["Rating"]

答案 1 :(得分:0)

通过为dnew列表中的每个元素遍历data['features']字典中的所有键,您会失去字典的好处。

E.Coms注意到您遇到的问题,但是仅检查列表中的第一项(data["features"][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]
相关问题