0

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

1

2 Answers 2

0

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.

2
  • Thank you for your help, but i have 100 rows of data and the orient = 'index' doesnt work with this method it returns, raise ValueError("DataFrame index must be unique for orient='index'.") ValueError: DataFrame index must be unique for orient='index'.
    – Obito8750
    Nov 17, 2021 at 17:55
  • This means that you have multiple similar values in the starting_airport column. The output you desired is thereby not possible (you can't have a dict with similar keys). I'm not sure what output you want then, but you could try this: df.groupby('starting_airport')[['destination_airport','airline','average_time_taken']].apply(lambda x: x.to_dict('r')).to_dict() Nov 17, 2021 at 18:36
0

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]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.