简体   繁体   English

有没有办法从其他键内的键获取值?

[英]Is there any way of getting values from keys inside other keys?

(first post sorry if i do this wrong) So I am making a bot (on discord) for me and my friends using discord.py (since python is the easiest code ever) and I've came across this. (首先发帖抱歉,如果我做错了)所以我正在为我和我的朋友使用discord.py制作机器人(不和谐)(因为python是有史以来最简单的代码)而且我遇到了这个。 I need to get values from keys INSIDE OTHER keys. 我需要从键INSIDE OTHER键获取值。 How do I do this? 我该怎么做呢?

So I've tried to change res to res.text and res.json and res.content and I could only find the "data" but not "id","name" or "description" which I need. 所以我试图将res更改为res.text和res.json以及res.content,我只能找到“数据”但不能找到我需要的“id”,“name”或“description”。

import discord
from discord.ext.commands import Bot
from discord.ext import commands
import requests, json
import asyncio

Client = discord.Client()
client = commands.Bot(command_prefix='?')
@client.event
async def on_ready():
    print('started')

@client.command()
async def findfriends(ctx,userid):
        res = requests.get("https://friends.roblox.com/v1/users/"+userid+"/friends")
        var = json.loads(res.text)
        def a(a):
                ID = a['id']
                return ID
        def b(b):
                Name = b['name']
                return Name
        def c(c):
                description = c['description']
                return description
        data = var['data'] #I can get this working
        print(data)
        #cv = data['name'] #but this wont work
        #id = a(var)       #nor this
        #name = b(var)     #nor this
        #desc = c(var)     #nor this
        #await ctx.send("\nID: " + id + "\nName: " + name + "\nDesc: " + desc) # this is just sending the message

client.run(BOT TOKEN HERE) #yes i did indeed add it but just for the question i removed it

As I said in the code, I can only get "data" working and not id,name or desc. 正如我在代码中所说,我只能使“数据”工作而不是id,name或desc。 For id name and desc it just throws an error 对于id name和desc,它只会抛出一个错误

Ignoring exception in command findfriends:
Traceback (most recent call last):
  File "C:\Users\Calculator\PycharmProjects\ryhrthrthrhrebnfbngfbfg\venv\lib\site-packages\discord\ext\commands\core.py", line 79, in wrapped
    ret = await coro(*args, **kwargs)
  File "C:/Users/Calculator/PycharmProjects/ryhrthrthrhrebnfbngfbfg/a.py", line 277, in findfriends
    id = a(var)       #nor this
  File "C:/Users/Calculator/PycharmProjects/ryhrthrthrhrebnfbngfbfg/a.py", line 266, in a
    ID = a['id']
KeyError: 'id'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\Calculator\PycharmProjects\ryhrthrthrhrebnfbngfbfg\venv\lib\site-packages\discord\ext\commands\bot.py", line 863, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\Calculator\PycharmProjects\ryhrthrthrhrebnfbngfbfg\venv\lib\site-packages\discord\ext\commands\core.py", line 728, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\Calculator\PycharmProjects\ryhrthrthrhrebnfbngfbfg\venv\lib\site-packages\discord\ext\commands\core.py", line 88, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: KeyError: 'id'

and

Ignoring exception in command findfriends:
Traceback (most recent call last):
  File "C:\Users\Calculator\PycharmProjects\ryhrthrthrhrebnfbngfbfg\venv\lib\site-packages\discord\ext\commands\core.py", line 79, in wrapped
    ret = await coro(*args, **kwargs)
  File "C:/Users/Calculator/PycharmProjects/ryhrthrthrhrebnfbngfbfg/a.py", line 274, in findfriends
    data = var['data']['id'] #I can get this working
TypeError: list indices must be integers or slices, not str

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\Calculator\PycharmProjects\ryhrthrthrhrebnfbngfbfg\venv\lib\site-packages\discord\ext\commands\bot.py", line 863, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\Calculator\PycharmProjects\ryhrthrthrhrebnfbngfbfg\venv\lib\site-packages\discord\ext\commands\core.py", line 728, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\Calculator\PycharmProjects\ryhrthrthrhrebnfbngfbfg\venv\lib\site-packages\discord\ext\commands\core.py", line 88, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: list indices must be integers or slices, not str

The https://friends.roblox.com/v1/users/<userid>/friends endpoint returns a list of all the friends that the user has, which can be of varying size. https://friends.roblox.com/v1/users/<userid>/friends端点返回用户拥有的所有朋友的列表,其大小可以不同。

With var = json.loads(res.text) you are loading the response text into a json object, which contains the key data , which you access using data = var['data'] . 使用var = json.loads(res.text)您将响应文本加载到json对象中,该对象包含您使用data = var['data']访问的密钥data The new data variable now contains a list object, which is why cv = data['name'] fails to work as list objects do not take strings as keys, they are accessed using integers. 新的data变量现在包含一个列表对象,这就是cv = data['name']无法工作的原因,因为列表对象不将字符串作为键,使用整数访问它们。

You need to iterate over the list to get all information on the friends. 您需要遍历列表以获取有关朋友的所有信息。 The below code goes through the list, pulls information for each item in the list and sends a message of the information once it has gone through all items. 下面的代码遍历列表,为列表中的每个项目提取信息,并在完成所有项目后发送信息消息。

import discord
from discord.ext.commands import Bot
from discord.ext import commands
import requests, json
import asyncio

client = commands.Bot(command_prefix='?')
@client.event
async def on_ready():
    print('started')

@client.command()
async def findfriends(ctx,userid):
    res = requests.get("https://friends.roblox.com/v1/users/"+userid+"/friends")
    var = json.loads(res.text)
    data = var['data']
    print(data)

    friends_msg = 'Friends information:'
    for friend in data:
        id = friend['id']
        name = friend['name']
        desc = friend['description']
        friends_msg = friends_msg + "\nID: " + id + "\nName: " + name + "\nDesc: " + desc

    await ctx.send(friends_msg)

client.run(BOT TOKEN HERE)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 根据键列表从字典中获取值 - Getting values from a dict according to a list of keys 任何从字典中形成字典的pythonic方法,其中很少有键具有列表值? - Any pythonic way to form dictionaries from dictionary where few keys have list values? 有没有办法用匹配的键将两个字典的对应值相互除法? - Is there a way to divide with each other the corresponding values of two dictionaries with matching keys? 对字典中的键内的值进行排序 - Sorting values inside keys in dictionary 使用Python中的对象和键数组从json数组获取值 - Getting values from json array using an array of object and keys in Python 从字典键和值中填充 dataframe:有效方式 - Filling a dataframe from a dictionary keys and values: efficient way AWS Cloudformation,使用 Python 从键中获取值的最佳方法 3 - AWS Cloudformation, best way to get values from keys with Python 3 如果键与另一字典的键匹配,则添加一个字典的值 - Adding values of one dictionary if the keys match the keys of the other dictionary 按字典中的第一个键分组并对其他键值内的值应用计算,python 字典? - Grouping by first key in a dict and apply calculations on values inside other keys values, python dict? 如果某些键相同,则添加字典的其他值 - Add the other values of a dictionary if certain keys are the same
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM