2016-11-19 61 views
7

如果我有這樣一個字典作爲如何在Julia中翻譯字典?

my_dict = Dict(
    "A" => "one", 
    "B" => "two", 
    "C" => "three" 
) 

什麼是扭轉鍵/值映射關係的最佳方式?

+0

您是否必須擔心映射到相同值的兩個不同鍵,或者不是? – DSM

回答

11

的一種方法是通過遍歷鍵/值對,沿途交換他們使用的理解來構建新字典:

julia> Dict(value => key for (key, value) in my_dict) 
Dict{String,String} with 3 entries: 
    "two" => "B" 
    "one" => "A" 
    "three" => "C" 

當交換鍵和值,您可能希望保留請記住,如果my_dict具有重複值(例如"A"),則新字典可能包含的鍵較少。另外,新字典中按鍵"A"定位的值可能不是您期望的值(Julia的字典不以任何容易確定的順序存儲其內容)。

14

假設你不必擔心重複值碰撞鑰匙,mapreverse你可以使用:

julia> my_dict = Dict("A" => "one", "B" => "two", "C" => "three") 
Dict{String,String} with 3 entries: 
    "B" => "two" 
    "A" => "one" 
    "C" => "three" 

julia> map(reverse, my_dict) 
Dict{String,String} with 3 entries: 
    "two" => "B" 
    "one" => "A" 
    "three" => "C" 
+0

這是最好的答案! –

4

使這個一會兒回來,可能有衝突值

function invert_dict(dict, warning::Bool = false) 
    vals = collect(values(dict)) 
    dict_length = length(unique(vals)) 

    if dict_length < length(dict) 
     if warning 
      warn("Keys/Vals are not one-to-one") 
     end 

     linked_list = Array[] 

     for i in vals 
      push!(linked_list,[]) 
     end 

     new_dict = Dict(zip(vals, linked_list)) 

     for (key,val) in dict 
      push!(new_dict[val],key) 
     end 
    else 
     key = collect(keys(dict)) 

     counter = 0 
     for (k,v) in dict 
      counter += 1 
      vals[counter] = v 
      key[counter] = k 
     end 
     new_dict = Dict(zip(vals, key)) 
    end 

    return new_dict 
end 
詞典

使用此如果如果一個關鍵成爲重複,你將有一個列表與所有值,所以沒有數據將會丟失,即

julia> a = [1,2,3] 
julia> b = ["a", "b", "b"] 

julia> Dict(zip(a,b)) 
Dict{Int64,String} with 3 entries: 
    2 => "b" 
    3 => "b" 
    1 => "a" 

julia> invert_dict(ans) 
Dict{String,Array} with 2 entries: 
    "b" => Any[2,3] 
    "a" => Any[1]