我想从 Julia 的 csv 文件中读取 5 个级别的嵌套字典。我有它的 Python 代码,但我不知道如何在 Julia 中做到这一点。有人可以帮忙吗?'
demand = {}
with open("demand.csv", 'r') as data_file:
data_file.readline()
for row in data_file:
row = row.strip().split(",")
demand.setdefault(row[0],{}).setdefault(row[1],{}).setdefault(row[2],{}).setdefault(row[3],{})[row[4]] = (row[5])
你需要一个递归的 Dict 构造函数。与 Python 示例不同,这里有一个适用于任意数量的 >= 2 的列:
function makeifnone(dict::Dict, list::Vector)
if length(list) < 2
throw("List depth too shallow to get a key=>value pair in makeifnone()")
elseif length(list) == 2
dict[list[1]] = list[2]
else
k = popfirst!(list)
if !haskey(dict, k)
dict[k] = Dict()
end
makeifnone(dict[k], list)
end
end
demand = Dict()
open("demand.csv", "r") do data_file
readline(data_file)
rows = readlines(data_file)
for row in rows
entries = split(strip(row), ",")
makeifnone(demand, entries)
end
println(demand)
end
我没有你的 csv,但是有这个 csv 文件:
Name,Birthdate,State,Relation,Email,Notes
Sally Whittaker,1988-12-05,Illinois,friend,[email protected],student
Belinda Jameson,1994-02-17,California,family,[email protected],cousin
Jeff Bragg,2018-10-10,Texas,family,[email protected],brother-in-law
Sandy Allen,2002-03-09,Colorado,friend,[email protected],ex
Fred Kobo,1967-10-10,Colorado,friend,[email protected],brother to Belinda
Nate Smith,1983-04-22,Colorado,family,[email protected],nephew
我得到与 Python 相同的结果,尽管 Python 版本打印时没有类型符号。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句