Python Forum
Getting values from a dictionary
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Getting values from a dictionary
#1
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...
Reply
#2
Depends on the structure of the data. This does look pretty clear, what are you looking for?
Reply
#3
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
Reply
#4
(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)  
Reply
#5
(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:
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

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?
Reply
#6
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))
Output:
time high low open volumefrom volumeto close conversionType conversionSymbol 1616716800 33.01 32.01 32.36 14147.54 459354.17 32.39 invert 1616803200 32.93 32.19 32.39 14604.07 475135.19 32.62 invert 1616889600 33.10 32.58 32.62 12160.02 399198.72 33.08 invert 1616976000 33.11 31.50 33.08 16051.11 517814.86 31.73 invert 1617062400 32.23 31.54 31.73 14830.86 474005.03 31.92 invert 1617148800 32.34 30.28 31.92 21814.13 688238.39 30.71 invert
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  need to compare 2 values in a nested dictionary jss 2 846 Nov-30-2023, 03:17 PM
Last Post: Pedroski55
  Printing specific values out from a dictionary mcoliver88 6 1,368 Apr-12-2023, 08:10 PM
Last Post: deanhystad
Question How to print each possible permutation in a dictionary that has arrays as values? noahverner1995 2 1,728 Dec-27-2021, 03:43 AM
Last Post: noahverner1995
  Python dictionary with values as list to CSV Sritej26 4 2,985 Mar-27-2021, 05:53 PM
Last Post: Sritej26
  Conceptualizing modulus. How to compare & communicate with values in a Dictionary Kaanyrvhok 7 3,954 Mar-15-2021, 05:43 PM
Last Post: Kaanyrvhok
  Adding keys and values to a dictionary giladal 3 2,464 Nov-19-2020, 04:58 PM
Last Post: deanhystad
  In this dictionary all the values end up the same. How? Pedroski55 2 1,923 Oct-29-2020, 12:32 AM
Last Post: Pedroski55
  Counting the values ​​in the dictionary Inkanus 7 3,586 Oct-26-2020, 01:28 PM
Last Post: Inkanus
  How to make a list of values from a dictionary list? faryad13 2 2,054 Sep-03-2020, 03:45 PM
Last Post: faryad13
  access dictionary with keys from another and write values to list redminote4dd 6 3,220 Jun-03-2020, 05:20 PM
Last Post: DeaD_EyE

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020