TransWikia.com

Using user input to retrieve data

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.

One Answer

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

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP