简体   繁体   English

从Python中的列表列表创建词典列表

[英]Creating a list of dictionaries from a list of lists in Python

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 我的问题是关于如何从列表列表中创建词典列表,并且与列表列表和问题列表到字典 列表的此问题Dict Comprehension python 有所不同

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] 我设法将其转换为带有towers.values(towers是数据框的名称)的列表的列表,其中每个列表的格式为[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? 我怎样才能做到这一点?

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. 正如@yatu所建议的,使用df.loc比链接索引要有效得多。


data = zip(df['Lat'].tolist(), df['Lon'].tolist())
[{'lat': a, 'lon': b} for a, b in data]

遍历数据帧的每一行可以提供解决方案。

res_list_of_dict = [{'lat':i[1][0], 'long':i[1][1]} for i in df.iterrows()]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM