Smooth dictionary in Julia

I have a dict in Julia

In[27]:  CollectedOutputCount
Out[27]: Dict{Any,Any} with 3 entries:
  2 => Any[278963,1,1]
  3 => Any[283339,1,1]
  1 => Any[272878,0,0,0]

I want to create an Array from the contents of a Dict consisting of the sum of each Dict 2: end record. The first value in each Dict entry is the label. The result should be something like

Output = [ label sum;label sum;...]

in this case it will be

Output = [278963 2;283339 2;272878 0]

Is there a way to do this separately from iteration in loops? Is there any function to smooth Dict into an array (possibly with padding where there are uneven sizes)?

+4
source share
2 answers

I'm not sure about functions that can smooth out dictionaries in the same way, but you can avoid loops using map:

Given your dictionary:

CollectedOutputCount = Dict(2 => [278963,1,1], 3 => [283339,1,1], 1 => [272878,0,0,0], 4 => [1234])

You can flatten it to [label sum; label sum ...] in one line:

vcat(map(a -> [a[1] sum(a[2:end])], values(CollectedOutputCount))...)

What gives you:

4x2 Array{Int64,2}:
1234  0
278963  2
283339  2
272878  0

map , . , vcat. , sum 0, , 1 (1234 0).

+2

@niczky12, ;

>>> mydict =  Dict(2 => [278963,1,1], 3 => [283339,1,1], 
                   1 => [272878,0,0,0], 4 => [1234]);
>>> comp = [[a[1] sum(a[2:end])] for a in values(mydict)];

, map. ( ).

comp - , , 4 , 1x2. 4x2 array:

>>> vcat(comp...)
4x2 Array{Int64,2}:
   1234  0
 278963  2
 283339  2
 272878  0

, :

>>> mydict = Dict(2 => [278963,1,0], 3 => [283339,1,1], 1 => [272878,0,0])
>>> vals = hcat(values(mydict)...)';
>>> hcat(vals[:, 1], sum(vals[:, 2:end], 2))
3x2 Array{Int64,2}:
 278963  1
 283339  2
 272878  0

, , , .


, , :

r = zeros(Int64, length(mydict), 2)
for (n, b) in enumerate(values(mydict))
    r[n, 1] = b[1]
    r[n, 2] = sum(b[2:end])
end
+1

All Articles