How do I access elements of a json that contains multiple keys in python?

Asked

Viewed 74 times

0

I’m practicing learning Apis with HG Finance , but when I filter the information through a FOR , I see that presents an error called KeyError: nome da moeda, But the code runs the same way, I’d like to understand how to get the exact information out of a json with multiple arrays and how to get that error out. follows my code below:

import requests
arquivo = open('C:/Users/Usuario/PycharmProjects/Aprendizado/ pass.txt', mode='r')
senha =arquivo.read()
requests= requests.get("https://api.hgbrasil.com/finance/quotations?key={}".format(senha))
dados = requests.json()
moeda= input("Moeda Desejada: ")
for x in dados['results'].values():
    for z in x[moeda].items():
        print(z)

1 answer

0


One of the ways is to pass the Keys(keys) explicitly:

import requests
requests= requests.get("https://api.hgbrasil.com/finance/quotations?key={}")
dados = requests.json()

moeda = input("Moeda Desejada: ").upper()

for item in dados['results']['currencies'][moeda].items():
    print(item)

Entree:

Moeda Desejada: usd

Exit:

('name', 'Dollar')
('buy', 5.393)
('sell', 5.4116)
('variation', 0.04)

Can display everything on one line as well:

dados['results']['currencies'][moeda]

Exit:

{'name': 'Dollar', 'buy': 5.393, 'sell': 5.4116, 'variation': 0.04}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.