通过运行csv文件d,使用Python脚本创建字典列表

2024-09-25 08:34:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下格式的数据

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”位置追加到一个列表中

我希望我的数据是在我提到的特定形式,以便与数据可视化代码,我有工作。我确信创建我想要的格式需要一个思想上的飞跃,但是我不确定要做什么来满足这个要求。我也不知道我需要的输出类型应该是一个列表还是一个数组,并希望对此进行澄清

请帮我解决这个问题,提前谢谢


Tags: csvto数据from列表字典格式自行车
2条回答

我想这应该管用

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)

^{}可能是解决这个问题的好方法

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)

相关问题 更多 >