0

My question is on how to create a list of dictionaries from a list of lists, and is a deviation from this question Dict Comprehension python from list of lists and this question List of Lists to List of Dictionaries

I have a very long pandas data frame with latitudes and longitudes as such

     LAT        LON
     40         5
     40         6
     41         5
     42         8
     42         9

I managed to transform it into a list of lists with towers.values(towers is the name of the dataframe) in which each list is of the format [lat,lon]

My goal is to have

list_dict = [{'lat': 40, 'lon': 5}, 
             {'lat': 40, 'lon': 6}, 
             {'lat': 41, 'lon': 5},
             {'lat': 41, 'lon': 5},
             {'lat': 42, 'lon': 8},
             {'lat': 42, 'lon': 9}]

How can I do this?

yatu
  • 86,083
  • 12
  • 84
  • 139
Nocas
  • 357
  • 1
  • 4
  • 14

2 Answers2

2
list_dict = [{'lat': df.loc[i, 'Lat'], 'lon' : df.loc[i, 'Lon']} for i in range(df.shape[0])]

As @yatu proposed, It's much more efficient to use the df.loc than a chained index.


data = zip(df['Lat'].tolist(), df['Lon'].tolist())
[{'lat': a, 'lon': b} for a, b in data]
ComplicatedPhenomenon
  • 4,055
  • 2
  • 18
  • 45
0

Iterating over each row of dataframe can give the solution.

res_list_of_dict = [{'lat':i[1][0], 'long':i[1][1]} for i in df.iterrows()]
Akash Pagar
  • 637
  • 8
  • 22