2016-03-26 10 views
8

Qual è il modo migliore per unire un dizionario in Julia?In Julia, come unire un dizionario?

> dict1 = Dict("a" => 1, "b" => 2, "c" => 3) 
> dict2 = Dict("d" => 4, "e" => 5, "f" => 6) 
# merge both dicts 
> dict3 = dict1 with dict2 
> dict3 
Dict{ASCIIString,Int64} with 6 entries: 
    "f" => 6 
    "c" => 3 
    "e" => 5 
    "b" => 2 
    "a" => 1 
    "d" => 4 

risposta

7

http://docs.julialang.org/en/latest/stdlib/collections/#Base.Dict

merge(collection, others...) 

Construct a merged collection from the given collections. If necessary, the types of the resulting collection will be promoted to accommodate the types of the merged collections. If the same key is present in another collection, the value for that key will be the value it has in the last collection listed. 

julia> merge(dict1,dict2) 
    Dict{ASCIIString,Int64} with 6 entries: 
     "f" => 6 
     "c" => 3 
     "e" => 5 
     "b" => 2 
     "a" => 1 
     "d" => 4 

merge!(collection, others...) 
Update collection with pairs from the other collections. 

julia> merge!(dict1,dict2) 
Dict{ASCIIString,Int64} with 6 entries: 
    "f" => 6 
    "c" => 3 
    "e" => 5 
    "b" => 2 
    "a" => 1 
    "d" => 4 

julia> dict1 
Dict{ASCIIString,Int64} with 6 entries: 
    "f" => 6 
    "c" => 3 
    "e" => 5 
    "b" => 2 
    "a" => 1 
    "d" => 4 
+1

Appena fuori se la curiosità, come sarebbe quindi gestire in conflitto valori chiave? Se ho valori 'a = 5' in 'dict1' e 'a = 7' in 'dict2' quale sarebbe il valore di 'a' nel dizionario risultante? – niczky12

+1

@ niczky12 sarà aggiornato a 7, l'ultimo valore. –

+1

Se si desidera mantenere i valori in conflitto, è possibile utilizzare 'union (dict1, dict2)'; tuttavia, ciò restituirebbe un 'array' piuttosto che un 'Dict'. –