2014-02-26 92 views
0

Python字典今天真的有我。我一直在傾吐堆棧,試圖找到一種方法來對Python字典中的現有密鑰做一個新值的簡單追加,並且我在每次嘗試時都會失敗,並使用我在此處看到的相同語法。將多個值添加到Python字典中的單個鍵

這就是我要做的:

#cursor seach a xls file 
definitionQuery_Dict = {} 

for row in arcpy.SearchCursor(xls): 

    # set some source paths from strings in the xls file 
    dataSourcePath = str(row.getValue("workspace_path")) + "\\" + str(row.getValue("dataSource")) 
    dataSource = row.getValue("dataSource") 

    # add items to dictionary. The keys are the dayasource table and the values will be definition (SQL) queries. First test is to see if a defintion query exists in the row and if it does, we want to add the key,value pair to a dictionary. 
    if row.getValue("Definition_Query") <> None: 

     # if key already exists, then append a new value to the value list 
     if row.getValue("dataSource") in definitionQuery_Dict: 
      definitionQuery_Dict[row.getValue("dataSource")].append(row.getValue("Definition_Query")) 
     else: 
      # otherwise, add a new key, value pair 
      definitionQuery_Dict[row.getValue("dataSource")] = row.getValue("Definition_Query") 

我得到一個屬性錯誤:

AttributeError: 'unicode' object has no attribute 'append'

但我相信我做的一樣的答案提供here

我嘗試了各種其他方法,但沒有與其他各種錯誤消息一起運行。我知道這可能很簡單,也許我無法在網上找到正確的來源,但我被卡住了。任何人都在意幫忙嗎?

謝謝, 邁克

回答

3

的問題是,你原來設置的值是一個字符串(即的row.getValue結果),但隨後試圖將其追加如果它已經存在。您需要將原始值設置爲包含單個字符串的列表。將最後一行更改爲:

definitionQuery_Dict[row.getValue("dataSource")] = [row.getValue("Definition_Query")] 

(請注意圓括號的值)。

ndpu使用defaultdict有一個好處:但是如果你使用的是,你應該始終做append - 即用if語句中的append替換整個if/else語句。

+0

呃...我知道我需要這樣的東西。將值設置爲列表。我想我只是看着太多的例子,然後我迷惑了自己。這正是我需要的。謝謝! – Mike

2

使用collections.defaultdict

from collections import defaultdict 

definitionQuery_Dict = defaultdict(list) 
# ... 
+0

因此,只需導入defaultdict,然後將我的變量從definitionQuery_Dict = {}更改爲definitionQuery_Dict = defaultdict(list)?如果是這樣,我仍然得到相同的錯誤.... – Mike

2

你的字典有鍵和值。如果您想隨時添加值,則每個值都必須是可以擴展/擴展的類型,如列表或其他字典。目前,字典中的每個值都是一個字符串,而您想要的卻是包含字符串的列表。如果您使用的列表,你可以這樣做:

mydict = {} 
records = [('a', 2), ('b', 3), ('a', 4)] 

for key, data in records: 
    # If this is a new key, create a list to store 
    # the values 
    if not key in mydict: 
     mydict[key] = [] 
    mydict[key].append(data) 

輸出:

mydict 
Out[4]: {'a': [2, 4], 'b': [3]} 

注意,即使'b'只有一個值,即單個值仍然需要放在一個列表,因此它可以在稍後添加。

相關問題