Lists inside a dictionary
After this: Keep a list for each key, add to one list through its key, and count across all of them.
On this page · 5 sections · 3 checks
A sports day has teams, and each team has players. Red has Ana and Ben; blue has Cy. You want to look a team up by its name and get its players, and you want to add a player to a team. A list of rows does not fit, because the teams have names, not numbers. A dictionary fits, as "Dictionaries and sets" taught: look things up by name. What is new is that the value under each name is a list.
A dictionary whose values are lists
In the last two lessons a list held lists. A dictionary can hold lists in the same way: each key has a list as its value. This is nested data again, a list inside a dictionary.
| Key | Value |
|---|---|
"red" | ["Ana", "Ben"] |
"blue" | ["Cy"] |
Reading goes in two steps, as it did for a cell of a table. The key picks the list; a position picks the value. Work through teams["red"][0]teams.get("red").get(0) by hand:
- teams["red"]teams.get("red") picks the list under red:
["Ana", "Ben"]. - [0].get(0) picks position 0 of that list: Ana.
Left to right, one step at a time, the same rule as grid[1][2].
Counting across all the teams
How many players are there in all? Each team's list has a length, and the answer is the lengths added up. So the loop goes through the lists, and the running total adds each length. teams.values()teams.values() gives the lists one at a time, without their keys.
countstarts at 0.- The loop picks the list under red,
["Ana", "Ben"], length 2:countbecomes 2. - It picks the list under blue,
["Cy"], length 1:countbecomes 3. - The loop is finished. 3 is printed.
- Run the programRun it. Line 2 (Java: line 10) reaches one player with a key and then a position. Then watch players take each team's list in turn, and count grow by its length.
teams = {"red": ["Ana", "Ben"], "blue": ["Cy"]}print(teams["red"][0])count = 0for players in teams.values(): count = count + len(players)print(count)run the program to see its boxes
nothing printed yetPress Run it, then step through the program one line at a time.
- lines
- 0
- prints
- 0
- calls
- 0
Python runs in the browser below; Java is traced above.
Change the 0 to 1 and run again. Then add a third team and see the count change.
Adding a player, adding a team
To add a player to a team, reach the team's list through the dictionary, then add to it the way "Lists" taught. teams["blue"].append("Dee")teams.get("blue").add("Dee"); looks up the list under blue and puts Dee at its end. No new pair is made: the list that was already in the dictionary grows. Count the players afterwards and there are four, where there were three.
Step through a smaller dictionary, one player per team, so that the box stays readable. Line 210 changes the blue list inside it; nothing else moves.
teams = {"red": ["Ana"], "blue": ["Cy"]}teams["blue"].append("Dee")print(teams["blue"])count = 0for players in teams.values(): count = count + len(players)print(count)run the program to see its boxes
nothing printed yetPress Run it, then step through the program one line at a time.
- lines
- 0
- prints
- 0
- calls
- 0
To add a whole team, add a pair, as in "Dictionaries and sets", with a list as the value.
teams = {"red": ["Ana", "Ben"], "blue": ["Cy"]}teams["green"] = ["Eve"]print(len(teams))print(teams["green"][0])3 Eve
HashMap<String, ArrayList<String>> teams = new HashMap<>();teams.put("red", new ArrayList<>(List.of("Ana", "Ben")));teams.put("blue", new ArrayList<>(List.of("Cy")));teams.put("green", new ArrayList<>(List.of("Eve")));System.out.println(teams.size());System.out.println(teams.get("green").get(0));3 Eve
The dictionary then has three pairs, and Eve can be reached with the key green and position 0.
Check yourself
teams holds {"red": ["Ana", "Ben"], "blue": ["Cy"]}red → [Ana, Ben] and blue → [Cy]. What is teams["red"][0]teams.get("red").get(0)?
Dee joins the blue team. How many players does the program count?
teams = {"red": ["Ana", "Ben"], "blue": ["Cy"]}teams["blue"].append("Dee")count = 0for players in teams.values(): count = count + len(players)print(count)HashMap<String, ArrayList<String>> teams = new HashMap<>();teams.put("red", new ArrayList<>(List.of("Ana", "Ben")));teams.put("blue", new ArrayList<>(List.of("Cy")));teams.get("blue").add("Dee");int count = 0;for (ArrayList<String> players : teams.values()) { count = count + players.size();}System.out.println(count);Complete the missing line so that Dee is added to the blue team and the program prints 2, the length of the blue list.
teams = {"red": ["Ana", "Ben"], "blue": ["Cy"]}____________________ # ← add Dee to the blue teamprint(len(teams["blue"]))HashMap<String, ArrayList<String>> teams = new HashMap<>();teams.put("red", new ArrayList<>(List.of("Ana", "Ben")));teams.put("blue", new ArrayList<>(List.of("Cy")));____________________ // ← add Dee to the blue teamSystem.out.println(teams.get("blue").size());Honesty notes
- Keep a list for each key, so a dictionary of teams holds a list of players under each team name.
- Reach a player with a key and then a position: the key picks the list, the position picks the value.
- Add a player through the dictionary by looking up the team's list and adding to it; add a team by adding a new pair.
- Count across all the lists with a loop over the values, adding each list's length to a running total.