perero
perero

Reputation: 21

Python Dictionary key within a key

I don't know how to write this correctly.

Candy = {"sweetness": 1}
jonny = {"holding": Candy}
print(jonny["holding"["sweetness"]])

Basically I want the sweetness of whatever jonny is holding. Also, what jonny is holding will change throughout the script.

Upvotes: 1

Views: 2013

Answers (3)

deadbeef404
deadbeef404

Reputation: 623

As others have pointed out the correct way is:

jonny["holding"]["sweetness"]

The reason why is that jonny["holding"] returns the value of holding in the jonny dict. The value of jonny["holding"] in this case is the Candy dictionary.

jonny["holding"] == Candy

Therefore, if you can do Candy["sweetness"] then by simple substitution, you can then do jonny["holding"]["sweetness"]

You can nest dictionaries or lists to any level using this concept by following that pattern, eg:

jonny["holding"]["sweetness"]["otherkey"][0]["another_key"]["etc"]

Upvotes: 2

Marcin
Marcin

Reputation: 238111

You need to do as follows:

print(jonny["holding"]["sweetness"])

Upvotes: 1

levi
levi

Reputation: 22697

Just.

print(jonny["holding"]["sweetness"])
>> 1

jonny["holding"] gives to you Candy dict. So, then get sweetness key from it.

Upvotes: 2

Related Questions