user44557
user44557

Reputation: 99

Accessing dictionary values within a dictionary

I have a dictionary velocity.

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

I'm trying to access the values of "mag" and "dir" within "x".

This is how I tried to do it:

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

How should I do this?

Upvotes: 0

Views: 89

Answers (2)

John1024
John1024

Reputation: 113814

I think that you may want to define velocity as:

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

That way, your assignment statement will work:

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

Upvotes: 2

MattDMo
MattDMo

Reputation: 102842

The values of the x and y keys are tuples, not dicts, so you need to use tuple indexing to access them:

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

So, your assignment should be:

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

To make it more straightforward, make velocity a dict of dicts:

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

Upvotes: 1

Related Questions