2014-02-21 157 views
-4

我正在使用返回字符串列表的方法。類似於:包含字符串的列表字典

a=get_all_elements() 

我想使用「a」中的字符串並創建列表字典。例如:

dict = { element1, element2, element3} 

這裏再次element1是一個字符串列表,它將由另一個返回字符串列表的方法填充。例如:

data = {'element1': [string1, string2, string3], 'element2': [string1, string2, string3]...} 

我該怎麼做?

+5

字典是鍵值對容器類,所以' {element1,element2,element3}'不是*字典。 – thefourtheye

+2

字典是python中的關鍵字。不要用於變量名稱。 – ilmiacs

+0

dict = {element1,element2,element3} 它應該是列表: [element1,element2,element3] –

回答

1

此代碼:

a = get_all_elements() 
mydict = {ai:[] for ai in a} 

將創建一個空列表的字典:

mydict['element1'].append('stringN') 

或創建列表:

{'element1':[], 'element2':[], 'element3':[]} 

然後你就可以通過附加的字符串來填充它:

mydict['element1'] = [s for s in create_strings()] 

如果此功能需要的元素作爲參數,你可以簡單地做:

mydict = {ai:[s for s in create_strings(ai)] for ai in a} 
0

可以使用defaultdict對象,看http://docs.python.org/2/library/collections.html#collections.defaultdict

>>> keys = ['a','b','c'] 
>>> values = [['x','y','z'], ['d','e','f'], ['o','p','q']] 
>>> from collections import defaultdict 
>>> x = defaultdict(list) 
>>> for i,j in zip(keys, values): 
...  for k in j: 
...    x[i].append(k) 
... 
>>> for i in x: 
...  print i, x[i] 
... 
a ['x', 'y', 'z'] 
c ['o', 'p', 'q'] 
b ['d', 'e', 'f']