Victor
Victor

Reputation: 152

Getting the keys, and not the values

So I want to get the json keys and compare them with the variable q

Json file

{
  "api_key": "YOUR AUTOBUY API KEY",
  "prefix": "PREFIX FOR BOT COMMANDS (for e.x !redeem, ?claim, etc",
  "redeem_message": "Thanks for redeeming your order for {0}, I have added the ROLE_NAME_HERE role.",
  "role_id": "REPLACE THIS WITH THE ID OF THE ROLE YOU WANT TO GIVE UPON REDEEMING",
  "redeem_channel_id": "REPLACE THIS WITH THE CHANNEL ID WHERE PEOPLE CAN USE THE REDEEM COMMAND",
  "bot_token": "PUT YOUR DISCORD BOT TOKEN HERE"
}

Code

import json

def search(q):
    with open("config.json") as f:
        data = json.load(f)
        for obj in data:
            print(data[obj])
search(q="role_id")

Expected output: REPLACE THIS WITH THE ID OF THE ROLE YOU WANT TO GIVE UPON REDEEMING (cause q = role_id and I want it to return the value of the key)

Actual output:

YOUR AUTOBUY API KEY
PREFIX FOR BOT COMMANDS (for e.x !redeem, ?claim, etc
Thanks for redeeming your order for {0}, I have added the ROLE_NAME_HERE role.
REPLACE THIS WITH THE ID OF THE ROLE YOU WANT TO GIVE UPON REDEEMING
REPLACE THIS WITH THE CHANNEL ID WHERE PEOPLE CAN USE THE REDEEM COMMAND
PUT YOUR DISCORD BOT TOKEN HERE

Upvotes: 0

Views: 59

Answers (2)

balderman
balderman

Reputation: 23815

below

data = {'A':12,'B':13}

q = 'A2'

value = data.get(q)
if value is not None:
    print(value)
else:
    print('{} not found'.format(q))

Upvotes: 0

Thomas
Thomas

Reputation: 181745

Super simple, no need for a for loop if you just need one value:

import json

def search(q):
    with open("config.json") as f:
        data = json.load(f)
        print(data[q])
search(q="role_id")

Upvotes: 1

Related Questions