2014-02-26 95 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'只有一个值,即单个值仍然需要放在一个列表,因此它可以在稍后添加。

相关问题