![]() |
Getting values from a dictionary - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Getting values from a dictionary (/thread-33127.html) |
Getting values from a dictionary - brunolelli - Mar-31-2021 Hello guys, I'm using the following API project in order to collect some data from Flight Radar 24. https://pypi.org/project/FlightRadarAPI/ In the project's documentation it's written that: You can also get more information about a specific flight such as: aircraft images, estimated time, trail, etc. details = fr_api.get_flight_details(flight.id) flight.set_flight_details(details) print("Flying to", flight.destination_airport_name)So, in order to get the value of some 'fields' I'm using the following expression: print(details['time']['real']['departure']) print(details['time']['real']['arrival']) print(details['time']['estimated']['departure']) print(details['time']['estimated']['arrival'])My question is: Is there any better and more 'inteligent' way of doing this? Basically my intention is to loop through all flights of some airlines... RE: Getting values from a dictionary - jefsummers - Mar-31-2021 Depends on the structure of the data. This does look pretty clear, what are you looking for? RE: Getting values from a dictionary - deanhystad - Mar-31-2021 Are you just trying to print information? You can print the dictionary or sub-dictionaries like this: print('Real time', details['time']['real']) If you don't like how that looks you could try the pretty print library. https://docs.python.org/3/library/pprint.html RE: Getting values from a dictionary - brunolelli - Mar-31-2021 (Mar-31-2021, 08:21 PM)jefsummers Wrote: Depends on the structure of the data. This does look pretty clear, what are you looking for? I would like to add it in my code and export the information to a TXT file. this is the code i'm currenty running import csv import time import sched, time from datetime import datetime from FlightRadar24.api import FlightRadar24API fr_api = FlightRadar24API() empresas = ['JES', 'DAP', 'GLO', 'THT', 'BWA'] while True: try: now = datetime.now() day = datetime.today() current_time = now.strftime("%H:%M") current_day = day.strftime("%d/%m/%y") for i in range(0,len(empresas)): flights = fr_api.get_flights(airline = empresas[i]) #print(type(flights[0])) #print(flights[0].__dict__) print("Dados da empresa: ", empresas[i], " atualizado as: ", current_time) with open(r'C:\Users\bruno\Desktop\Voos\DB\Voos.txt', 'a', newline='') as f: fieldnames = ['dia_analisado', 'hora_analisada', 'data', 'hora', 'airline_icao', 'callsign', 'aircraft_code', 'registration', 'origin_aiport_iata', 'destination_airport_iata', 'latitude', 'longitude', 'heading', 'altitude', 'ground_speed', 'on_ground', 'vertical_speed', 'squawk' ] # you can include whatever attributes you want wrtr = csv.DictWriter(f, fieldnames=fieldnames, extrasaction='ignore', delimiter=';') #wrtr.writeheader() for flight in flights: flight.data = datetime.fromtimestamp(flight.time).strftime("%d/%m/%y") # convert the timestamp to datetime object flight.hora = datetime.fromtimestamp(flight.time).strftime("%H:%M:%S") flight.hora_analisada = current_time flight.dia_analisado = current_day wrtr.writerow(flight.__dict__) # here I pass all attributes as dict, but you can always access individual attributes, like I did with time above time.sleep(60) except: print('Olha deu erro, mas vou tentar novamente!') time.sleep(10) RE: Getting values from a dictionary - brunolelli - Mar-31-2021 (Mar-31-2021, 08:39 PM)deanhystad Wrote: Are you just trying to print information? You can print the dictionary or sub-dictionaries like this: I would like to add it in my code and export the whole information to a TXT file. How can I incorporate this new set of code to my project? RE: Getting values from a dictionary - snippsat - Mar-31-2021 It can be easier if take data first into Pandas,then get out all kind of formats. A example and for plain text can use df.to_string .import requests import pandas as pd # Api url = 'https://min-api.cryptocompare.com/data/histoday?fsym=BTC&tsym=ETH&limit=5&aggregate=1&e=CCCAGG' data = requests.get(url).json()['Data'] # To Pandas df = pd.DataFrame.from_dict(data) # To txt with open('out.txt', 'w') as f: f.write(df.to_string(index=False))
|