Keep the dictionary unchanged

Hi everyone,

I have a dictionary D1 and I´d like to create a new dictionary D2 with the same keys as D1 and
by replacing all the values in each key of D1.
I did this :

for i in 1:length(CT)
   D2 = Dict(k => (D1[k] .= CT[i]) for k in keys(D1))
end

This works but the D1 dictionary also changes. How can I keep the values in D1 unchanged?

Thank you,

The key question is how the indices of CT are supposed to relate to the keys of D1 but without more information I would suggest

D2 = Dict(k => CT[k] for k in keys(D1))

df1 = DataFrame(Column1 = [“c”,“b”,“c”,“c”,“b”,“c”],
Column2 = [“Value1”,“Value2”,“Value3”,“Value1”,“Value2”,“Value3”],
Column3 = [“Value1”,“Value2”,“Value3”,“Value1”,“Value2”,“Value3”] )

df2 = DataFrame(Column1 = [“c”,“b”],
Column2 = [8,9],
Column3 = [“Value1”,“Value2”,])

So the array CT = [8,9] from column 2 of df2
D1 = Dict(“c” = [1,3,4,6] , “b” = [2,5]) has as keys c and b and as values the indexes of c and b in the dataframe df1
D2 = Dict(“c” = [8,8,8,8] , “b” = [9,9]) has as keys c and b and as values what corresponds to c and b in CT.

k is a string so I can´t use it as an index.

Sorry, I’ve never used DataFrames and I don’t understand the logic of what you’re trying to do, so I’ll leave this to someone with better insights.

Ok, thanks for trying to help me !

Dict(k => fill(CT[i], size(D1[k])...) for k in keys(D1)) might work. Do note that Julia’s dictionaries aren’t ordered, so the double iteration you’re doing can probably yield unexpected values.

If you mutate the vectors that you store in D1, then yes, D1 will be changed. You need to copy the vectors if you need separate instances for both dictionaries.

So maybe (without trying it out)

for i in 1:length(CT)
   D2 = Dict(k => (copy(D1[k]) .= CT[i]) for k in keys(D1))
end
2 Likes

Thank you it worked !