Reputation: 21
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
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
Reputation: 22697
Just.
print(jonny["holding"]["sweetness"])
>> 1
jonny["holding"]
gives to you Candy
dict. So, then get sweetness
key from it.
Upvotes: 2