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': ''

dashe = {
    'name': 'dashe',
    'retail': '$200',
    'website': ''

favbot = input('What is your favorite bot? ')


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/", line 18, in <module>
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': ''
}, {
    'name': 'dashe',
    'retail': '$200',
    'website': ''

Then when you ask the use for a name, find it in the list

favbot = input('What is your favorite bot? ')
    found = next(item for item in bots if item["name"] == favbot)
    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("Not found")

Answered by Johnny Mopp on January 1, 2022

Add your own answers!

Related Questions

modal pop up after clicking button

1  Asked on August 19, 2020 by ashmoe


How to import react libraries into pure jsx file

0  Asked on August 17, 2020 by dannycranfield


Style changing with JS not responding

0  Asked on August 14, 2020 by alessandro


Can’t use saved information to load into an array

1  Asked on August 13, 2020 by danny


How to return pointer adress for structure variable

2  Asked on August 9, 2020 by mystheman


Merging two PDF generating views in Django

1  Asked on August 8, 2020 by piethon


How do you put a list inside of an object C#?

1  Asked on August 8, 2020 by forrest


How to modify this C++ class to be as efficient as C code?

1  Asked on August 7, 2020 by victor-canoz


Ask a Question

Get help from others!

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