首页 > 解决方案 > 预先分配一个字典的字典

问题描述

当我在以下函数上运行 @code_warntype 时(以粗体显示的是可能引发危险信号的表达式。)

function cardata(df::DataFrame,Emission_val::Float64,search_cars::Dict{String,Tuple{Int64,Int64}}=Dict("Car1" => (1000,10000), "Car2" => (1000,50000), "Car3" => (1000,6000)),
    all_cars::Array{String,1}=["Car1","Car2","Car3","Car4","Car5","Car6"])
    **species = Dict()**
    # The data file containing car information of interest 
    car_library = joinpath(path,"cars.csv")
    df_car_data=CSV.read(car_library,header=["Model","Velocity","Emission_Value","Mass","Column6"],delim='\t')

    #delete unused column
    deletecols!(df_car_data, :Column6)

    #create a new column with only the car Identifier name
    df_car_data[:Identifier_car]=[split(i,r"[0-9]+")[1] for i in df_car_data[:Model]]

    #get the properties of all_cars from the cars_data table
    for search_models in all_cars
        **cars[search_models] = Dict()**
        for i in 1:1:length(df_cars_data[1])
            num = split(df_cars_data[:Model][i],r"[0-9]+")[1]
            alpha = split(df_cars_data[:Model][i],r"[a-zA-Z]+")[2]
            if ( num == search_models )
                species[num][alpha] = df_car_data[:Velocity][i] 
            end
        end
    end
end

我收到以下以红色突出显示的警告:

Body::Tuple{Dict{Any,Any},Union{DataFrame,DataFrameRow{DataFrame,Index}},Any,Any}. 

假设我知道将填充字典的数据长度,如何在这种情况下为字典预分配类型?

标签: julia

解决方案


您没有提供最小的工作示例。看看下面的代码。请注意,出于效率原因,建议使用Symbol密钥而不是String

species = Dict{Symbol,Dict{Symbol,Float64}}()
group = get!(()->Dict{Symbol,Float64}(),species,Symbol("audi"))
group[Symbol("a4")]=10.5
group[Symbol("a6")]=9.5

现在打印输出:

julia> println(species)
Dict(:audi=>Dict(:a6=>9.5,:a4=>10.5))

推荐阅读