I used pandas to read the csv file and was able to create a dictionary from it but need to create the dictionary as a specific format.
flightinfo = pd.read_csv('flightdata.csv',quotechar='"',names=['starting_airport', 'destination_airport', 'airline', 'time', 'start_state','end_state'], header=None)
flightinfodict = flightinfo.to_dict(orient='records')
this gives the output
[{'starting_airport': 'Hilo International Airport', 'destination_airport': 'Boise Airport ', 'airline': 'delta', 'average_time_taken': 300, 'start_state': 'HAWAII', 'end_state': 'IDAHO'}
but the output i need is
{'Hilo International Airport' : {'destination_airport': 'Boise Airport ', 'airline': 'delta', 'average_time_taken': 300}
how can i modify the code to produce this output
thanks
CodePudding user response:
There may be a more sophisticated way of doing it, but this processing of the record-oriented dict should do the job:
def get_dict_without(d, key_to_remove):
d.pop(key_to_remove)
return d
new_flightinfodict = [{rec["starting_airport"]: get_dict_without(rec, "starting_airport")} for rec in flightinfodict]
CodePudding user response:
Set starting_airport
as index and use to_dict(orient='index')
:
flightinfodict.set_index('starting_airport').to_dict(orient='index')
Output:
{'Hilo International Airport': {'destination_airport': 'Boise Airport ',
'airline': 'delta',
'average_time_taken': 300,
'start_state': 'HAWAII',
'end_state': 'IDAHO'}}
Or:
df.set_index('starting_airport')[['destination_airport','airline','average_time_taken']].to_dict(orient='index')
since you indicate you need only these three columns in the dict.