2014-01-06 115 views
0

我有一本字典velocity在字典中訪問字典值

velocity = {"x": ({"mag": 5}, {"dir", 1}), "y": ({"mag": 5}, {"dir", 1})}

我試圖內"x"訪問"mag""dir"值。

這是我想做到這一點:

self.position["x"] += (self.velocity["x"]["mag"] * self.velocity["x"]["dir"])

我應該怎樣做呢?

+0

這不是在字典詞典。 –

回答

2

我認爲你可能要定義爲速度:

velocity = {"x":{"mag": 5, "dir": 1}, "y": {"mag": 5, "dir": 1} } 

這樣,你的賦值語句將工作:

position["x"] += (velocity["x"]["mag"] * velocity["x"]["dir"]) 
1

xy鍵的值的元組,而不是類型的字典,所以你需要使用的元組索引來訪問它們:

​​

所以,你的任務應該是:

self.position["x"] += (self.velocity["x"][0]["mag"] * self.velocity["x"][0]["dir"]) 

爲了使它更直接,使velocity一個字典:

{'x': {'mag': 5, 'dir': 1}, 'y': {'mag': 5, 'dir': 1}}