Aqyl
Aqyl

Reputation: 61

How to search through multiple dicts/literals with user input

I understand my title probably isn't exactly what I need mainly because I don't know how to articulate what I'm supposed to be looking for otherwise I would just look it up if I knew what it was called. I made an API request to a site and got this as a JSON response using result['bots']:

[{'id': 97, 'category': 'shopify,footsites,yeezysupply', 'color': '#333b56', 'image': 'https://i.imgur.com/LYQO1qo.png', 'maintenance': False, 'maintenance_message': None, 'name': 'MekAIO', 'twitter': None, 'url': '/products/mekaio'}, {'id': 96, 'category': 'shopify,supreme,footsites,yeezysupply', 'color': '#1f1e2b', 'image': 'https://i.imgur.com/hPJp35q.png', 'maintenance': False, 'maintenance_message': None, 'name': 'Nebula', 'twitter': 'nebulabots', 'url': '/products/nebula'}, {'id': 92, 'category': 'collectibles', 'color': '#d4a3da', 'image': 'https://res.cloudinary.com/dklrin11o/image/twitter_name/w_600/scottbotv1.jpg', 'maintenance': False, 'maintenance_message': None, 'name': 'Scottbot', 'twitter': 'scottbotv1', 'url': '/products/scottbot'}] 

Here I have 3 dicts (I think that's what it's called). I want to be able to have a user input the 'name' and have it pull up all the info related to that 'name'. Each bot has an id, category, color, image, maintenance status, maintenance_message, name, twitter, and url.

Here is essentially what I want to happen:

What bot info would you like to view? Scottbot

so the user has said they want to see Scottbot's info and it would pull up Scottbot's dict:

{'id': 92, 'category': 'collectibles', 'color': '#d4a3da', 'image': 'https://res.cloudinary.com/dklrin11o/image/twitter_name/w_600/scottbotv1.jpg', 'maintenance': False, 'maintenance_message': None, 'name': 'Scottbot', 'twitter': 'scottbotv1', 'url': '/products/scottbot'}

Here is the code I have written:

import requests

userInput = input('What bot do you want info on? ')

if userInput == 'scottbot':
    not really sure what to put here

url = 'https://api.botbroker.io/api/v2/bots'
headers={"x-api-key" : 'myAPIKEY'}
response = requests.get(url, headers=headers)
result = response.json()

print(result['bots'][0])

I tried formatting the [0] by using [{}].format(userInput) where my then statement had the correct number of the dict, but that didn't work. I just want it to where I can search by the names and then pull up the proper dicts related to the name. I hope that made sense, I'm still not the best with Python. Go easy on me please lol.

Upvotes: 1

Views: 59

Answers (1)

MiConnell
MiConnell

Reputation: 46

This little function will return the right dictionary

def get_name_info(name, lst):
    for dct in lst:
        if name == dct["name"]:
            return dct

just pass "Scottbot" and the list of dictionaries into it.

Upvotes: 1

Related Questions