2017-02-13 144 views
0

我有一本字典和一組如下:Python字典鍵來新字典

fundprices = { 
'A' : 20, 
'B' : 20, 
'C' : 10, 
'D' : 15, 
'E' : 10, 
'F' : 15, 
'G' : 35, 
'H' : 20, 
'I' : 10, 
'J' : 5 
} 

dollaramount = { 
100000.0, 
100000.0, 
50000.0, 
300000.0, 
50000.0, 
100000.0, 
100000.0, 
150000.0, 
50000.0, 
0 
} 

,我試圖創建第三個字典,是一組由字典劃分的結果,具有以下代碼:

orderamount = [] 

for i in fundprices.key(), dollaramount.key(): 
    orderamount.append(dollaramount[i]/fundprices[i]) 

print orderamount 

其中orderamount與基金價格具有相同的關鍵。但是,我得到'dict'對象沒有任何屬性。在這種情況下,dollaramount是由2個字典的另一個計算創建的集合。如果設置dollaramount時創建密鑰更容易,請告訴我。我該如何解決?

+6

第二個對象不是字典。它是一套。 –

+4

其實,它甚至不是一套 - 那裏有一個多餘的右括號。另外,如果你將第一個分爲第一個,那麼你將得到一個被零除的錯誤。 – SiHa

+2

'dollaramount'與'fundprices'有什麼關係?回想一下,字典是無序的。' –

回答

0
from collections import OrderedDict 
fundprices = { 
    'A' : 20, 
    'B' : 20, 
    'C' : 10, 
    'D' : 15, 
    'E' : 10, 
    'F' : 15, 
    'G' : 35, 
    'H' : 20, 
    'I' : 10, 
    'J' : 5 
    } 

dollaramount = [ 
    100000.0, 
    100000.0, 
    50000.0, 
    300000.0, 
    50000.0, 
    100000.0, 
    100000.0, 
    150000.0, 
    50000.0, 
    0] 
ordered_fundprices = OrderedDict(sorted(fundprices.items())) 
for i, j in zip(ordered_fundprices.keys(), dollaramount): 
    print i, j 

for i, j in zip(ordered_fundprices.itervalues(), dollaramount): 
    print j/i 

你想要這樣的結果嗎?

A 100000.0 
B 100000.0 
C 50000.0 
D 300000.0 
E 50000.0 
F 100000.0 
G 100000.0 
H 150000.0 
I 50000.0 
J 0 
5000.0 
5000.0 
5000.0 
20000.0 
5000.0 
6666.66666667 
2857.14285714 
7500.0 
5000.0 
0 
+0

你不能依賴這種行爲 - 字典是無序的,這將給不同的運行/不同的python版本等隨機結果。順便說一句,你不需要使用'鍵'方法遍歷'dict'鍵 - 會自動發生,並且在Python 2中效率低下,在Python 3中是不必要的和冗餘的。 –

+0

不,結果總是相同的。因爲鍵的順序被指定一次,直到這個對象的生命結束。我會同意,這不是命令。當運行此循環作爲第三個時,請注意相同的順序: '對於i,j in zip(fundprices.itervalues(),dollaramount): print j/i a.append(j/i)' ' ,j in zip(fundprices.keys(),a): print i,j' –

+0

但是,在運行代碼之前,您無法知道您將得到哪些比率*,並且OP不太可能需要隨機比率。所以是的,只要你不修改字典,你會得到相同的結果,但你不知道結果會是什麼,因爲字典是無序的*。 –

0

使用list代替setdollaramount實際上euqals到,

set([0, 50000.0, 100000.0, 150000.0, 300000.0]) 

然後,我們有,

orderamount = [amount/t[1] for amount, t in zip(dollaramount, sorted(fundprices.items()))] 

print(orderamount) 
# [5000.0, 5000.0, 5000.0, 20000.0, 5000.0, 6666.666666666667, 2857.1428571428573, 7500.0, 5000.0, 0] 

如果你想有一個記住鍵是順序的字典首先插入,使用collections.OrderedDict

+0

老實說,將排序後的結果(fundprices.items())放在OrderedDict中是沒有意義的,隨後迭代'items' ...只是使用sortd(fundprices.items ())'直接... –

+0

@ juanpa.arrivillaga,thx。我爲了可讀性的目的而做了它。無論如何,我剛剛更新了我的答案。 – SparkAndShine