I have a nested dictionary and instead of a hard coded query to query for ownername John I want to prompt the user for a name and just to test it, I type John upon being prompted and the program crashes with an error that says string indices must be integers.
The below works fine and returns Kitty.
John = { 1: {'name': 'Kitty', 'kind': 'cat'},
2: {'name': 'Ruffle', 'kind': 'dog'},
3: {'name': 'Bobby', 'kind': 'fish'}
}
petownername = John[1]['name']
print(petownername)
This also works fine when I hardcode the owner_name to John and I input the dictionary query with f string.
John = { 1: {'name': 'Kitty', 'kind': 'cat'},
2: {'name': 'Ruffle', 'kind': 'dog'},
3: {'name': 'Bobby', 'kind': 'fish'}
}
owner_name = John
petname = f"{owner_name[1]['name']}"
print(petname)
But as mentioned above when I add new user input it stops working
John = { 1: {'name': 'Kitty', 'kind': 'cat'},
2: {'name': 'Ruffle','kind': 'dog'},
3: {'name': 'Bobby',' kind': 'fish'}
}
owner_name = str(input("Which pet owner do you want to look up?: "))
petname = f"{owner_name[1]['name']}"
print(petname)
I am getting this error:
Which pet owner do you want to look up?: John
Traceback (most recent call last):
File "test3.py", line 9, in <module>
petname = f"{owner_name[1]['name']}"
TypeError: string indices must be integers
So it works fine when I hardcode it and insert it via f string and input is clearly a string. Any idea why it's not working on user prompt? Do I need to store and refer back to the user prompt in another way perhaps?