Scott Nimrod
Scott Nimrod

Reputation: 11595

How can I generate a dictionary from a list?

How can I generate a dictionary from a list?

Take the following list:

let numbers = [1;2;2;3;3;3;4;5;5;]

How can I generate a dictionary where the key is the element and the value is the number of times that the element occurs within the list?

My sad attempt:

let numbers = [1;2;2;3;3;3;4;5;5;]
numbers |> Seq.fold (fun accumulator element -> Map.add (element, element list???) 0)

Upvotes: 1

Views: 523

Answers (2)

Daniel
Daniel

Reputation: 47904

Your example code uses Map, but, assuming Dictionary like you said, such a function could be written:

Seq.countBy id >> dict

Upvotes: 0

FoggyFinder
FoggyFinder

Reputation: 2220

Use Seq.groupBy

let numbers = [1;2;2;3;3;3;4;5;5]

let map = numbers |> Seq.groupBy id |> Map.ofSeq 

map |> Map.iter (printfn "%A - %A")

Print:

1 - seq [1]
2 - seq [2; 2]
3 - seq [3; 3; 3]
4 - seq [4]
5 - seq [5; 5]

Link:

https://dotnetfiddle.net/xyNyzn

Edit:

If you want to get : number - frequency (now using Seq.fold :))

let addElement (acc:Map<int,int>) element = 
    if acc.ContainsKey element then acc.Add(element, acc.[element] + 1) 
    else acc.Add(element, 1)

(Map.empty, numbers)
||> Seq.fold (addElement)
|> Map.iter (printfn "%A - %A")

Print:

1 - 1
2 - 2
3 - 3
4 - 1
5 - 2

Link:

https://dotnetfiddle.net/yFw4Jq

Upvotes: 3

Related Questions