Li Haoyi
Li Haoyi

Reputation: 15802

F#: Iterating over a dictionary just returns itself?

let h = dict [(1, 2), (3, 4)]
Console.WriteLine(h.Count)
for i in h do
    Console.WriteLine(i)

gives me

1
[(1, 2), (3, 4)]

Two questions. Firstly, why does iterating over a dict give me back a sequence which only has 1 item, the dict itself? There is probably some logic behind this that will also affect other things I end up trying to iterate over. What does this mean for all the other Seq members exposed by dict (Any(), All(), Aggregate(), etc.)?

Secondly, is there a good way to iterate over and generally manipulate the key-value pairs in the dictionary, like in Python?

Upvotes: 0

Views: 725

Answers (1)

Brian
Brian

Reputation: 118865

You used a comma where you need a semicolon.

[(1,2); (3,4)]

Commas for tuples, semicolons for list elements. (The parens here are optional.)

If you want to iterate over key-value pairs in the dictionary, you can use

for KeyValue(k,v) in someDictionary do ...

which uses the KeyValue active pattern.

Upvotes: 11

Related Questions