Home
F#
dict: Dictionary Examples
Updated Nov 23, 2023
Dot Net Perls
Dict. In F# programs we often need to map keys to values—a color name might have an index value. We could use a dict to make these links.
Type info. A dict is read-only: we create it once and cannot modify its contents. We use the dict keyword. A Dictionary, which can be changed, may also be used when mutability is needed.
Item example. Let us begin with a simple example. We create a "colors" dictionary with string keys and int values. This is a read-only sequence of key-value pairs.
Info Dict allows quick construction of a lookup table. For simple requirements, this is a good choice.
Also Item returns the value for a key in the dict. We use printfn with an "%A" to print the int value returned.
// Create a dictionary with 2 key-value pairs. let colors = dict["blue", 40; "red", 700] // Print value of "blue" key. printfn "%A" (colors.Item("blue")) // Print value of "red" key. printfn "%A" (colors.Item("red"))
40 700
Count, for-loop. A dict has many features—it supports all of the methods from the IDictionary interface. Often we must count, or iterate over, a dict's contents.
Info Count returns an int. Here we see our dict has two key-value pairs. We store this value in the constant "c."
Next We use a for-in loop to print all the values of the dict. We use a do keyword to indicate the start of the loop body.
// Create a dictionary with dict keyword. let sizes = dict["small", 0; "large", 10] // Get count of pairs and display it. let c = sizes.Count printfn "%A" c // Loop over pairs in the dictionary. // ... Display each KeyValuePair. for pair in sizes do printfn "%A" pair
2 [small, 0] [large, 10]
Keys. With this property we get a collection of the keys in the dict. With this collection (which is not a list) we can use a function like Seq.iter. Here we print all the keys.
Seq
fun
printfn
let places = dict["Canada", 10; "Germany", 20] // Get keys in a collection. let keys = places.Keys // Display all keys with labels. Seq.iter (fun key -> printfn "Key = %A" key) keys
Key = "Canada" Key = "Germany"
Error. A dict is read-only. It is immutable. This means we cannot set or add items (keys or values) to it. To add keys we must create a new dict.
// Create a lookup table. let lookup = dict["100", false; "200", true] // This causes an exception. lookup.Item("300") <- false
Unhandled Exception: System.NotSupportedException: This value cannot be mutated
Key-value pairs. We can use the dict keyword with existing key-value pairs. We can create these pairs with tuple syntax. Then we just pass them into the dict expression.
Tuple
EntryPoint
[<EntryPoint>] let main argv = let pair = ("carrot", "orange") let pair2 = ("apple", "red") // Use dict with Key-Value pairs already created. let fruit = dict[pair; pair2] // Write the Count. printfn "COUNT: %d" fruit.Count 0
COUNT: 2
A review. A dict is immutable in F#. This helps with functional programming, but sometimes we want a more versatile lookup table. We use a Dictionary for this purpose.
Final notes. Special F# constructs like dict can be used with other constructs like the tuple syntax. We can use a 2-item tuple to create an entry in a dict. Immutability is retained.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Nov 23, 2023 (edit link).
Home
Changes
© 2007-2025 Sam Allen