繁体   English   中英

访问词典中的词典值

[英]Accessing dictionary values within a dictionary

我的字典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"] )

我应该怎么做?

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

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

这样,您的工作分配声明将起作用:

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

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

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

因此,您的任务应该是:

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

为了使它更简单,使velocity成为命令的命令:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM