2013-05-19 144 views
0

我想創造詞典在Python的字典:動態字典的Python

假設我已經有一個包含密鑰列表:

keys = ['a', 'b', 'c', 'd', 'e'] 
value = [1, 2, 3, 4, 5] 

假設我有一個數據字段的數值(其中20)

我想要定義,其存儲與給定到相應的值

for i in range(0, 3) 
    for j in range(0, 4) 
    dictionary[i] = { 'keys[j]' : value[j] } 
個不同的字典的字典

因此,基本上,它應該是這樣的:

dictionary[0] = {'a' : 1, 'b' : 2, 'c' : 3, 'd': 4, 'e':5} 
dictionary[1] = {'a' : 1, 'b' : 2, 'c' : 3, 'd': 4, 'e':5} 
dictionary[2] = {'a' : 1, 'b' : 2, 'c' : 3, 'd': 4, 'e':5} 
dictionary[3] = {'a' : 1, 'b' : 2, 'c' : 3, 'd': 4, 'e':5} 

什麼是實現這一目標的最佳途徑?

+0

你對[dict.copy()](http://docs.python.org/library/stdtypes.html#dict.copy)感興趣嗎? – mg007

回答

3

使用列表理解和dict(zip(keys,value))將返回字典給你。

>>> keys = ['a', 'b', 'c', 'd', 'e'] 
>>> value = [1, 2, 3, 4, 5] 
>>> dictionary = [dict(zip(keys,value)) for _ in xrange(4)] 
>>> from pprint import pprint 
>>> pprint(dictionary) 
[{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}, 
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}, 
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}, 
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}] 

如果你想類型的字典字典,然後使用字典理解:

>>> keys = ['a', 'b', 'c', 'd', 'e'] 
>>> value = [1, 2, 3, 4, 5] 
>>> dictionary = {i: dict(zip(keys,value)) for i in xrange(4)} 
>>> pprint(dictionary) 
{0: {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}, 
1: {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}, 
2: {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}, 
3: {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}} 
0

的詞典列表:

dictionary = [dict(zip(keys,value)) for i in xrange(4)] 

如果你真的想詞典的詞典喜歡你說:

dictionary = dict((i,dict(zip(keys,value))) for i in xrange(4)) 

我想你可以使用流行或其他字典呼叫,你不能從列表

順便說一句:如果這是一個真正的數據/數字處理應用程序,我會建議移動到numpy和/或熊貓作爲偉大的模塊。

編輯重:OP意見, 如果你想要的數據類型indicies你正在談論:

# dict keys must be tuples and not lists 
[(i,j) for i in xrange(4) for j in range(3)] 
# same can come from itertools.product 
from itertools import product 
list(product(xrange4, xrange 3)) 
+0

這可以繼續使用索引,如:dictionary = for i in xrange(4)):for j in range(0,3):dict((i,dict(zip(keys [j],value [j])) ) – dawg

+0

假設值也被定義爲雙數組=>值[i] [j],其中每個元素在矩陣中不同 – dawg

1

的替代,只有拉鍊一次...:

from itertools import repeat 
map(dict, repeat(zip(keys,values), 4)) 

或者,也許只是使用dict.copy並構建一次dict

[d.copy() for d in repeat(dict(zip(keys, values)), 4)]