Practice 3 - Dictionaries & Integers

Hello Again :sweat_smile: This time is about the logic behind “For each” condition and dictionaries.

I replicated the solution to understand completely the exercise but I have some problems in these steps:

Variables:

Winners: New Dictionary(Of Int32,String) From {{2006,“Oscar Pereiro”},{2007,“Alberto Contador”}, {2008, “Carlos Sastre”}, {2009,“Alberto Contador”}, {2010, “Andy Schleck”}, {2011, “Cadel Evans”}, {2012,“Bradley Wiggins”}, {2013,“Chris Froome”}, {2014,“Vincenzo Nibali”},{2015,“Chris Froome”},{2016,“Chris Froome”},{2017,“Chris Froome”}, {2018,“Geraint Thomas”}}

In the first “For Each” where we use “.Values” Function, what is does is to create a new dictionary called “WinnerName” and has all the values from “Winners”, please, correct me if I’m wrong

In the next step, If condition:

WinnerCounts.ContainsKey(WinnerName)

WinnerCounts is the variable(dictionary string,Int32)

.ContainsKey function determines whether the dictionary(WinnerName?) contains tthe key (names) ?

This is the step I don’t understand, when is created this dictionary with all the names?

WinnerName is not a dictionary. It’s just a String value in a list of Strings.
Let’s try to visualize the progress of the loop here.

Winners.Values returns a list of Strings which is iterated over, in this loop.

As the loop progresses, the control checks if a name exists in the list or not, and depending on the result, adds or increments another dictionary value, where the NAME is the KEY.

2 Likes

wow man, that is amazing, thanks. I have understood this completely.

Winners.Values Just represent the values part of the dictionary.

WinnerCounts is a empty dictionary, therefore, has no keys, so it adds those names as a key item.

thanks

1 Like

Yes, precisely!
Glad I could make it easy for you. :slightly_smiling_face:

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.