我正在尝试从从URL中提取的字典中获取特定值,在URL中,用户输入了项目名称,并且需要查找项目的编号,我不确定如何编写命令。我是python和dict的新手。
sign
用户输入的数据是锤子,我需要从以下信息中选择1。
import discord
from discord.ext import commands
import requests
import json
class Test:
def __init__(self, bot):
self.bot = bot
@commands.command()
@commands.has_any_role("Admin","Moderator")
async def it(self, ctx , *, name):
test = await self.bot.pg_con.fetchval("SELECT name FROM item WHERE name = $1", name)
if name != "None":
user = await self.bot.pg_con.fetchval("SELECT item_id FROM item where LOWER(name)= $1 ", name)
if user is not None:
with open(r'.\\cogs\config.json','r') as json_file:
data = json.load(json_file)
key = data["key"]
url = "https://api.torn.com/torn/" f"{user}" "?selections=items&key=" f"{key}"
data = requests.get(url).text
dict = json.loads(data)
print(dict)
name1 = dict['items'][user]['name']
print(name1)
weapon = dict['items'][user]['type']
description = dict['items'][user]['description']
market = dict['items'][user]['market_value']
buy = dict['items'][user]['buy_price']
sell = dict['items'][user]['sell_price']
embed = discord.Embed(title=f"{name1}",description=f"{description}",colour=discord.Color.dark_blue())
embed.set_footer(text=ctx.author.name,icon_url=ctx.author.avatar_url)
embed.add_field(name="Type", value="{}".format(weapon),inline=False)
embed.add_field(name="Market Value",value=f"$""{}".format(market),inline=True)
embed.add_field(name="Torn Buy Price",value=f"$""{}".format(buy),inline=True)
embed.add_field(name="Torn Sell Price",value=f"$""{}".format(sell),inline=True)
await ctx.send(embed=embed)
else:
await ctx.send("BAN Laz! Ban Laz!")
with open(r'.\\cogs\config.json', 'r') as json_file:
data = json.load(json_file)
key = data["key"]
url = "https://api.torn.com/torn/?selections=items&key=" f"{key}"
data = requests.get(url).text
dict = json.loads(data)
我试图使其正常运行,但未成功。我收到类型错误:str对象不可调用。我可能以某种方式未正确执行操作。
{"items":{"1":{"name":"Hammer",
"description":"A small, lightweight tool used in the building industry. Can also be used as a weapon.",
"type":"Melee",
"buy_price":75, "sell_price":50, "market_value":74,
"circulation":1282843,
"image":"https:\/\/www.torn.com\/images\/items\/1\/large.png"}
}}
答案 0 :(得分:0)
如果您知道关键字(Hammer)是键“名称”下的值,则可以遍历所有项目。
item_found = None
for index, item_dict in data.items():
# index gets '1', item_dict gets the rest
if item_dict['name'] = keyword:
item_found = index
break
return item_found
您还可以尝试列表理解:
item_list = [key for (key, value) in data.items() if value == keyword]
这将返回项目列表。在正常情况下,输入数据字典将有多个项目,并且可能有多个锤子。