Attention | Topic was automatically imported from the old Question2Answer platform. | |
Asked By | Macryc |
Hi All-
Here’s my json dictionary:
{
"tomatoes": {"tomato1": "fresh","tomato2": "rotten"},
"carrots": {"carrot11": "fresh","carrot2": "rotten"}
}
I load/parse the file and save it to a variable called vegetables
.
Now:
print(vegetables["tomatoes"].tomato1)
prints out fresh
, as expected.
BUT, if I do:
var index = 1
var state = str("tomato",(index))
…which builds the string tomato1
and then try to use this to reference the key in the Disctionary, ie: print(vegetables["tomatoes"].state)
…I get an invalid get index “string” on base Dictionary.
Does the Dictionary not take a string as a key? How can I make this work?
I don’t want to type in the key manually each time, especially that my keys are going to be sequentially numbered (tomato1:, tomato2:, tomato3 etc) and I want to get the size of the dictionary and instance a button for each key and put its value on it, and I want to do this dynamically. Please help.
From your (maybe oversimplified) example, a list would be better
{
"tomatoes": ["fresh", "rotten"],
"carrots": ["fresh", "rotten"]
}
vegetables["tomatoes"][0]
Tim Martin | 2020-09-10 13:30