2013-10-07 50 views
0

我有一個大的geoJSON文件提供選舉地圖。我已經颳了一個網站,並將選區分區結果返回到一個如下所示的Python字典中:{u'605': [u'56', u'31'], u'602': [u'43', u'77']等...}關鍵字是區號,價值列表是第一個候選人的投票和第二個候選人的投票。從python字典更新geoJSON文件

我想用字典的結果來更新我的geoJSON文件 - 這就是所有的選民區 - 。在我的geoJSON文件中,我將區號作爲我的鍵/值對之一(例如 - "precNum": 602)。我將如何用字典的結果更新每個形狀?

我可以通過東西的GeoJSON的文件中像這樣的目標和循環:

for precincts in map_data["features"]: 
    placeVariable = precincts["properties"] 

    placeVariable["precNum"] 
    #This gives me the precinct number of the current shape I am in. 

    placeVariable["cand1"] = ?? 
    # I want to add the Value of first candidate's vote here 

    placevariable["cand2"] = ?? 
    # I want to add the Value of second candidate's vote here 

任何想法將是一個巨大的幫助。

+0

你可以發佈你的json文件的樣本嗎? – shshank

+0

當然。每個分區是一個看起來像這樣的對象:'{「type」:「Feature」,「id」:0,「properties」:{「preNum」:40,「SHAPE_AREA」:0.0},「geometry」:{鍵入「:」Polygon「,」coordinates「:[[[Coords here]]}}' – JonnyD

+0

看到我的答案。你正在嘗試做什麼? @JonnyD – shshank

回答

1

您可以更新它是這樣的。

your_dict = {u'605': [u'56', u'31'], u'602': [u'43', u'77']} 

for precincts in map_data["features"]: 

    placeVariable = precincts["properties"] 
    prec = placeVariable["precNum"] 

    if your_dict.get(prec): #checks if prec exists in your_dict 
     placeVariable["cand1"] = your_dict['prec'][0] 
     placevariable["cand2"] = your_dict['prec'][0] 
0

你的問題措辭混亂。 你需要更好地識別你的變數。

聽起來就像你想累積投票總數。 因此,想要:

  • 分區100:[1,200]
  • 分區101:[4,300]

添加到:

  • [5,1 500]

設定accum的累加器數組。你可以扔掉表決票從那裏來的時候,你只是添加信息:

for vals in map_data['features'].values(): 
    while len(accum) < len(vals): 
     accum.append(0) 
    for i in range(len(vals)): 
     accum[i] += vals[i] 

下面是一個例子程序,證明了解決方案:

>>> x = { 'z': [2, 10, 200], 'y' : [3, 7], 'b' : [4, 8, 8, 10 ] } 
>>> accum = [] 
>>> for v in x.values(): 
... while len(accum) < len(v): 
...  accum.append(0) 
... for i in range(len(v)): 
...  accum[i] += v[i] 
... 
>>> accum 
[9, 25, 208, 10] 
>>> 
+0

對不起凱文這不是我想要做的。我想用我的字典中的信息更新geoJSON文件中的信息。如果我的形狀在我的geoJSON中看起來像這樣:'{「type」:「Feature」,「id」:0,「properties」:{「preNum」:40,「SHAPE_AREA」:0.0},「geometry」 「type」:「Polygon」,「coordinates」:[[[Coords here]]]}'我想讓位於第40區的我的字典中的數據輸入到該形狀對象中,並將屬性更改爲屬性。 {「preNum」:40,「SHAPE_AREA」:0.0,「cand1」:70,「cand2」:14} – JonnyD