Stack Overflow Asked by phast on January 1, 2022
I am trying to use a user’s input to display specific information from a dictionary. Everything works fine besides the last print command. I enter ‘pd’ in hopes of it turning into print(pd[‘name’]) like the line above it but I get an error.
Here is my code.
pd = {
'name': 'project destroyer',
'retail': '$200',
'website': 'https://projectdestroyer.com/'
}
dashe = {
'name': 'dashe',
'retail': '$200',
'website': 'https://dashe.com/'
}
favbot = input('What is your favorite bot? ')
print(pd['name'])
print(favbot['name'])
Here is my output and error message.
What is your favorite bot? pd
project destroyer
Traceback (most recent call last):
File "/Library/Phxn/Code/botfnder/bot_dict.py", line 18, in <module>
print(favbot['name'])
TypeError: string indices must be integers
What is the difference in me manually entering pd[‘name’] as opposed to favbot = pd … favbot[‘name’]?
I have thoroughly searched this error and just can’t seem to understand how to fix it. Any help would be appreciated.
You might use a list of dictionaries:
bots = [
{
'name': 'project destroyer',
'retail': '$200',
'website': 'https://projectdestroyer.com/'
}, {
'name': 'dashe',
'retail': '$200',
'website': 'https://dashe.com/'
}]
Then when you ask the use for a name, find it in the list
favbot = input('What is your favorite bot? ')
try:
found = next(item for item in bots if item["name"] == favbot)
print(found)
except:
print("Not found")
Here's another way to do it with a loop, if you prefer that:
favbot = input('What is your favorite bot? ')
for bot in bots:
if bot["name"] == favbot:
print(bot)
break
else:
print("Not found")
Answered by Johnny Mopp on January 1, 2022
1 Asked on August 19, 2020 by ashmoe
1 Asked on August 18, 2020 by ken-setoguchi
4 Asked on August 18, 2020 by ityka-bandta
0 Asked on August 17, 2020 by ggokturk
multiprocessing python python 3 x python multiprocessing python multithreading
0 Asked on August 17, 2020 by dannycranfield
2 Asked on August 16, 2020 by william
1 Asked on August 15, 2020 by abhijeet-vipat
1 Asked on August 15, 2020 by mendy
0 Asked on August 14, 2020 by alessandro
1 Asked on August 14, 2020 by rogiller
1 Asked on August 13, 2020 by danny
3 Asked on August 12, 2020 by adi-shukla
2 Asked on August 11, 2020 by kuwir-singh
1 Asked on August 11, 2020 by saran3h
0 Asked on August 10, 2020 by user12217822
2 Asked on August 9, 2020 by shiwee
1 Asked on August 8, 2020 by piethon
1 Asked on August 7, 2020 by victor-canoz
Get help from others!
Recent Questions
Recent Answers
© 2023 AnswerBun.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP