访问字典中的字典值

时间:2014-01-06 01:11:09

标签: python python-2.7 dictionary

我有一本字典velocity

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

我正在尝试访问"mag""dir""x"的值。

这就是我尝试这样做的方式:

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

我该怎么做?

2 个答案:

答案 0 :(得分:2)

我认为您可能希望将速度定义为:

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

这样,您的赋值语句将起作用:

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

答案 1 :(得分:1)

xy键的值是元组,而不是dicts,因此您需要使用元组索引来访问它们:

>>> velocity['x'][0]['mag']
5

所以,你的任务应该是:

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

为了使其更直接,请使velocity成为dicts的词典:

{'x': {'mag': 5, 'dir': 1}, 'y': {'mag': 5, 'dir': 1}}
相关问题