0

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.

3
  • 1
    favbot is a string inputted by the user so favbot['name'] doesn't make sense. Commented Jul 24, 2020 at 17:21
  • You have to pass in integers instead of 'name' in favbot['name']. Commented Jul 24, 2020 at 17:24
  • @JohnnyMopp so what would be a solution to get pd['name'] from a user entering 'pd'? Also thanks for the idea of listing dictionaries, that is very helpful. Commented Jul 24, 2020 at 17:31

1 Answer 1

1

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")
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you. Is there anyway I could choose which individual value I want printed rather than the entire dictionary? Such as the retail price of Dashe, $200?
Sure, just change print(found) to print(found["retail"])
Perfect. Thank you for the quick and helpful responses.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.