Download presentation
Presentation is loading. Please wait.
1
Multi-Dictionaries, Nested Dictionaries, Sets
Advanced Dictionaries SoftUni Team Technical Trainers Software University
2
Table of Contents Multi-Dictionaries Nested Dictionaries Sets
A Dictionary Holding List of Values Nested Dictionaries A Dictionary Holding Another Dictionary Sets HashSet<T> SortedSet<T>
3
sli.do #extended-softuni
Questions? sli.do #extended-softuni
4
Dictionaries Holding a List of Values
Multi-Dictionaries Dictionaries Holding a List of Values © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.
5
Value List<int>
Multi-Dictionaries A dictionary could hold a set of values by given key Example: students may have multiple grades: Peter [5, 5, 6] Kiril [6, 6, 3, 4, 6] Dictionary<string, List<int>> grades; Key String Value List<int>
6
Example: Student Grades
Each student has a list of grades We can access the student’s grades by name: Value List<int> var grades = new Dictionary<string, List<int>>(); grades["Peter"] = new List<int>(); grades["Peter"].Add(5); grades["Peter"].Add(6); var kirilGrades = new List<int>() { 6, 6, 3, 4, 6 }; grades["Kiril"] = kirilGrades; Console.WriteLine(string.Join(" ", grades["Kiril"]); // Initialize the list Accessing list by key (Peter) Assigning list to key
7
Problem: Average Student Grades
Write a program to read student names + grades Print the grades + average grade for each student as shown below 7 Ivancho 5.20 Mariika 5.50 Ivancho 3.20 Mariika 2.50 Stamat 2.00 Mariika 3.46 Stamat 3.00 Ivancho -> (avg: 4.20) Mariika -> (avg: 3.82) Stamat -> (avg: 2.50)
8
Solution: Average Student Grades (1)
var grades = new Dictionary<string, List<double>>(); var n = int.Parse(Console.ReadLine()); for (int i = 0; i < n; i++) { var tokens = Console.ReadLine().Split(); var name = tokens[0]; var grade = double.Parse(tokens[1]); if (!grades.ContainsKey(name)) grades[name] = new List<double>(); grades[name].Add(grade); } // continued on next slide ... Make sure the list is initialized Add grade into list
9
Solution: Average Student Grades (2)
KeyValuePair<string, List<double> foreach (var pair in grades) { var name = pair.Key; var studentGrades = pair.Value; var average = studentGrades.Average(); Console.Write($"{name} -> "); foreach (var grade in studentGrades) Console.Write($"{grade:f2} "); Console.WriteLine($"(avg: {average:f2})"); } Key: string Value: List<string> Average value of the list
10
Dictionary Holding Dictionary Inside
BG UK USA Sofia 1,211,000 Plovdiv 338,657 London 8,674,000 Manchester 2,550,000 New York City, NY 8,406,000 Washington, DC 658,893 Nested Dictionaries Dictionary Holding Dictionary Inside © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.
11
Value: Dictionary <string, int>
Nested Dictionaries Dictionaries may hold another Dictionary<K,V> as value Example: population by country and city Value: Dictionary <string, int> BG UK USA Sofia 1,211,000 Plovdiv 338,657 London 8,674,000 Manchester 2,550,000 New York City, NY 8,406,000 Washington, DC 658,893 Key: string
12
Problem: Cities by Continent and Country
Write a program to read continents, countries and their cities, put them in a nested dictionary and print them 9 Europe Bulgaria Sofia Asia China Beijing Asia Japan Tokyo Europe Poland Warsaw Europe Germany Berlin Europe Poland Poznan Europe Bulgaria Plovdiv Africa Nigeria Abuja Asia China Shanghai Europe: Bulgaria -> Sofia, Plovdiv Poland -> Warsaw, Poznan Germany -> Berlin Asia: China -> Beijing, Shanghai Africa: Nigeria -> Abuja
13
Solution: Cities by Continent and Country (1)
var continentsData = new Dictionary<string, Dictionary<string, List<string>>>(); var n = int.Parse(Console.ReadLine()); for (int i = 0; i < n; i++) { var tokens = Console.ReadLine().Split(); var continent = tokens[0]; var country = tokens[1]; var city = tokens[2]; // continued on next slide Initialize the dictionary
14
Solution: Cities by Continent and Country (2)
Continent doesn’t exist create it if (!continentsData.ContainsKey(continent)) continentsData[continent] = new Dictionary<string, List<string>>(); if (!continentsData[continent].ContainsKey(country)) continentsData[continent][country] = new List<string>(); continentsData[continent][country].Add(city); } // continued on next slide... Country doesn’t exist Initialize cities Append a city to the country
15
Solution: Cities by Continent and Country (3)
foreach (var continentCountries in continentsData) { var continentName = continentCountries.Key; var countries = continentCountries.Value; Console.WriteLine($"{continentName}:"); foreach (var countryCities in countries) var countryName = countryCities.Key; var cities = countryCities.Value; Console.WriteLine(" {0} -> {1}", countryName, string.Join(", ", cities)); } Continent name Countries in the continent Country name Cities in the country
16
Multi and Nested Dictionaries
Exercises in Class © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.
17
HashSet<T> and SortedSet<T>
Sets HashSet<T> and SortedSet<T>
18
Sets in C# A set keeps unique elements HashSet<T>
Allows add / remove / search elements Very fast performance HashSet<T> Keeps a set of elements in a hash-table Elements are in no particular order Similar to List<T>, but a different implementation SortedSet<T> The elements are ordered incrementally
19
List<T> vs HashSet<T>
Fast "add", slow "search" and "remove" (pass through each element) Duplicates are allowed Insertion order is guaranteed HashSet<T> Fast "add", "search" and "remove" (hash-table behind) Does not allow duplicates Does not guarantee the insertion order
20
HashSet<T> – Example
HashSet<string> set = new HashSet<string>(); set.Add("Pesho"); set.Add("Pesho"); // Not added again set.Add("Gosho"); set.Add("Alice"); Console.WriteLine(string.Join(", ", set)); // Pesho, Gosho, Alice Console.WriteLine(set.Contains("Georgi")); // false Console.WriteLine(set.Contains("Pesho")); // true set.Remove("Pesho"); Console.WriteLine(set.Count); // 2
21
Problem: Record Unique Names
Read a sequence of names and print only the unique ones 8 Ivan Pesho Stamat Alice Peter 7 Lyle Bruce Alice Easton Shawn Peter 6 Roki Roki Roki
22
Solution: Record Unique Names
HashSet stores unique values var names = new HashSet<string>(); var n = int.Parse(Console.ReadLine()); for (int i = 0; i < n; i++) { var name = Console.ReadLine(); names.Add(name); } foreach (var name in names) Console.WriteLine(name); Add non-existing names only
23
SortedSet<T> – Example
SortedSet<string> set = new SortedSet<string>(); set.Add("Pesho"); set.Add("Gosho"); set.Add("Maria"); set.Add("Alice"); Console.WriteLine(string.Join(", ", set)); // Alice, Gosho, Maria, Pesho Ordered alphabeticaly
24
Problem: Group Continents, Countries and Cities
Write a program to read continents, countries and city names Keep them in alphabetical order, no duplicates allowed For each continent print all its countries with their towns 9 Europe Bulgaria Sofia Asia China Beijing Europe Poland Warsaw Europe Germany Berlin Europe Poland Poznan Asia China Shanghai Asia: China -> Beijing, Shanghai Europe: Bulgaria -> Sofia Germany -> Berlin Poland -> Poznan, Warsaw
25
Solution: Cities by Continent and Country (1)
var continentsData = new SortedDictionary<string, SortedDictionary<string, SortedSet<string>>>(); var n = int.Parse(Console.ReadLine()); for (int i = 0; i < n; i++) { var tokens = Console.ReadLine().Split(); var continent = tokens[0]; var country = tokens[1]; var city = tokens[2]; // continued on next slide Initialize the sorted dictionary
26
Solution: Cities by Continent and Country (2)
Continent doesn’t exist create it if (!continentsData.ContainsKey(continent)) continentsData[continent] = new SortedDictionary<string, SortedSet<string>>(); if (!continentsData[continent].ContainsKey(country)) continentsData[continent][country] = new SortedSet<string>(); continentsData[continent][country].Add(city); } // continued on next slide... Country doesn’t exist create it Add the city into country
27
Solution: Cities by Continent and Country (3)
foreach (var continentCountries in continentsData) { var continentName = continentCountries.Key; var countries = continentCountries.Value; Console.WriteLine($"{continentName}:"); foreach (var countryCities in countries) var countryName = countryCities.Key; var cities = countryCities.Value; Console.WriteLine(" {0} -> {1}", countryName, string.Join(", ", cities)); } Continent name Countries in the continent Country name Cities in country
28
Sets Exercises in Class
© Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.
29
Summary Multi-dictionaries allow keeping a collection as a dictionary value E.g. Dictionary<string, List<int>> Nested dictionaries allow keeping a dictionary as dictionary value E.g. Dictionary<string, Dictionary<string, int>> Sets allow keeping unique values in unspecified order No duplicates, fast add / search / remove SortedDictionary<K,V> / SortedSet<T> keep keys sorted
30
Advanced Dictionaries
© Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.
31
License This course (slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution- NonCommercial-ShareAlike 4.0 International" license Attribution: this work may contain portions from "Fundamentals of Computer Programming with C#" book by Svetlin Nakov & Co. under CC-BY-SA license © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.
32
Trainings @ Software University
Software University Foundation – softuni.org Software University – High-Quality Education, Profession and Job for Software Developers softuni.bg Software Facebook facebook.com/SoftwareUniversity Software University Forums – forum.softuni.bg © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.