通过运行csv文件数据,使用Python脚本创建字典列表
我有格式的数据通过运行csv文件数据,使用Python脚本创建字典列表,python,json,dictionary,csvtoarray,Python,Json,Dictionary,Csvtoarray,我有格式的数据 from to Location1 Location2 Location1 Location3 Location1 Location4 Location1 Location5 Location2 Location1 Location2 Location3 Location3 Location1 Location3 Location2 Location3 Location4 在csv文件中。这些数据绘制了从一个车站到另一个车站
from to
Location1 Location2
Location1 Location3
Location1 Location4
Location1 Location5
Location2 Location1
Location2 Location3
Location3 Location1
Location3 Location2
Location3 Location4
在csv文件中。这些数据绘制了从一个车站到另一个车站的自行车旅行地图,并取自芝加哥一家自行车租赁公司的网站
现在我有了基本的代码,可以获取每一行并将其添加到列表中,但它并没有像我所希望的那样在第二个索引中创建字典。我的脚本看起来像:
import csv
li = []
with open('Desktop/test_Q4_trips.csv', newline='') as csvfile:
reader = csv.reader(csvfile, delimiter=',')
for name, imports in reader:
li.append({
"name": name,
"imports": imports,
})
del li[0]
这是输出
[{"from": "Location1", "to": "Location2"}, {"from": "Location1", "to": "Location3"},
{"from": "Location1", "to": "Location4"}, {"from": "Location1", "to": "Location5"},
...]
我想把这些数据转换成这种格式
[{"from": "Location1", "to": ["Location2", "Location3", "Location4", "Location5"]},
{"from": "Location2", "to": ["Location1", "Location3"]},
{"from": "Location3", "to": ["Location1", "Location2", "Location4"]}, ...
].
换句话说,我想创建一个字典列表,其中每个字典在第一个索引中有一个值,在第二个索引中有一个(可变多个)值的列表。特别是,输出应在第二个索引中的列表中列出自行车租赁行程接收端的所有站点。为此,我想我必须创建一个带有for循环的脚本,该循环遍历左侧的“from”值,并将每个“from”对应的“To”位置追加到列表中
我希望我的数据采用我提到的特定形式,以便使用我拥有的数据可视化代码。我确信创建我想要的格式需要一个思想上的飞跃,但我不确定到底要做什么来满足这一点。我也不确定我需要的输出类型是列表还是数组,希望您能对此进行澄清
请帮我解决这个问题,提前谢谢。这可能是解决这个问题的好方法
from collections import defaultdict
d = defaultdict(list)
a = [{"from": "Location1", "to": "Location2"}, {"from": "Location1", "to": "Location3"},
{"from": "Location1", "to": "Location4"}, {"from": "Location1", "to": "Location5"}]
for o in a:
d[o['from']].append(o['to'])
print(d)
我想这应该行得通
import numpy as np
l = [{"from": "Location1", "to": "Location2"}, {"from": "Location1", "to": "Location3"},
{"from": "Location1", "to": "Location4"}, {"from": "Location1", "to": "Location5"}]
from_to = np.array(([d['from'] for d in l],[d['to'] for d in l])).T
froms = set(from_to[:,0])
out = []
for f in froms:
d = {}
mask = from_to[:,0]==f
d['from']=f
d['to'] = from_to[:,1][mask]
out.append(d)
我不认为您发布的格式是否有分隔符为“,”。这会给出输出
[{“Location1”:[“Location2”,“Location3”,“Location4”,“Location5”]}]
而不是[{“from”:“Location1”,“to”:[“Location2”,“Location3”,“Location4”,“Location5”]}
。你知道我该怎么把“from”和“to”添加到字典里吗?谢谢。哦,对不起,只需添加以下行:res=[{“from”:k,“to”:v}代表k,v在d.items()中。
结尾@AshokB.raifegreeat。最后一个问题:如何删除任何重复的输出,例如,如果数据中列出了两次行程路线,但我希望输出文件的“to”列中只有一条记录?在这种情况下,最好使用set而不是list。因此,您使用d=defaultdict(set)
而不是list
和d[o['from']]。添加(o['to'])
而不是append()