2014-09-19 147 views
0

我基本上是在閱讀一個CSV文件,並且正在創建一個名爲「City」的對象,該對象是使用傳遞給構造函數「city_constructor」的屬性創建的。 編輯:該文件在每行上有「城市」信息。我有我在努力更新類型的字典詞典,這需要在2種不同的類相關聯的密鑰值:在Python中更新詞典詞典

% d is an iterator obtained from dictReader = csv.DictReader(placesFile) 
% Defining my dict of dicts called places 
places = {"City":{}, "Country":{}} 

然後我嘗試添加新對象到我的類型的字典的字典如下,但這似乎沒有工作。有沒有辦法做到這一點?:

for d in dictReader: 
    new_City = city_constructor(d["Population"],d["Area"]) 
    places.update({"City":new_City}) 
+0

爲什麼你不只是做'地方[「市」] = new_City '? – shaktimaan 2014-09-19 00:19:44

+0

給出2個不同''new_City''內容的示例,以及''places''的預期最終內容可能會幫助您理解您自己的問題,並幫助我們爲您提供幫助。有幾個因素需要解釋,我強烈懷疑即使是問題的標題也是錯誤的。 – vaab 2014-09-19 00:50:22

回答

2

您應該可以更新您的places字典有:

places["City"] = new_City 

如果你的文件在每一行都有「城市」信息,那麼我猜你會在每一行上做new_City = city_constructor(d["Population"],d["Area"])。在這種情況下,你的places應該是這樣的:

places = {"City":[], "Country":[]} 

你會更新爲:

for d in dictReader: 
    new_City = city_constructor(d["Population"],d["Area"]) 
    places["City"].append(new_City) 

如果它是類型的字典詞典,那麼你的places的結構應是這樣的:

{ 
    "City": { 
     "City_1": <city_constructor(d["Population"],d["Area"]) of first line>, 
     "City_2": <city_constructor(d["Population"],d["Area"]) of second line>, 
     "City_3": <city_constructor(d["Population"],d["Area"]) of third line>, 
    } 
} 

也就是說,必須有一個新的關鍵字與每一條線遇到一個新的城市。可能是這樣的:

count = 0 
for d in dictReader: 
    new_City = city_constructor(d["Population"],d["Area"]) 
    _a_dict = {'City_{}'.format(count):new_City} 
    count += 1 
    places["City"].update(_a_dict) 
+0

謝謝。然而,我仍然需要「地方」成爲口號的字典,這是不是列表的字眼? – user131983 2014-09-19 00:34:29

+0

對於每條線上的每一個新城市,你認爲關鍵是什麼?由於城市出現多次(文件的每一行出現一次),會有一個涉及'places'變量的列表 – shaktimaan 2014-09-19 00:38:41

+0

非常感謝。我可以問一下「count」的用途是什麼? – user131983 2014-09-19 00:55:40

1

對於更新單個密鑰,您應該使用這樣的:

places["City"] = new_City 
+0

謝謝。然而,正如用戶Shaktimaan所說,我的文件在每一行都有「城市」信息。 – user131983 2014-09-19 00:36:53

1
for d in dictReader: 
    new_City = city_constructor(d["Population"],d["Area"]) 
    try: 
     places["City"].append(new_City) 
    except KeyError: 
     places["City"] = [new_City] 

至少我覺得......假設我明白你問什麼