F# dict: Dictionary Examples, Item and Keys

Create a dictionary with dict. Use Item, Keys and TryGetValue to access the dictionary.

Dict. A connection is made. A wolf howls in the dark of night. A cat has soft fur. We link things to values of things: in F# we could use a dict to make these links.

Read-only. 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.Keywords

Syntax. 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.

Dict: This keyword allows quick construction of a lookup table. For simple requirements, this is a good choice.

Item: This returns the value for a key in the dict. We use printfn with an "%A" to print the int value returned.

F# program that creates dictionary, gets values // Create a dictionary with two 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")) Output 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.

Count: This returns an int. Here we see our dict has two key-value pairs. We store this value in the constant "c."

For: 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.

F# program that uses count, for-loop on dict // 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 Output 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.SeqFunPrintfn
F# program that displays keys in dict 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 Output 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.
F# program that causes dict exception // Create a lookup table. let lookup = dict["100", false; "200", true] // This causes an exception. lookup.Item("300") <- false Output 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
F# program that uses Key-Value pairs, dict [<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 Output 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.

In this language, 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
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to