Instruction
Good job! It's time to wrap things up. Before we do this section's quiz, let's have a quick review of what we've covered:
- To iterate over dictionary keys, use either:
for k in dictionary:
or:
for k in dictionary.keys():
- To iterate over dictionary values, use:
for v in dictionary.values():
- To get both values and keys during dictionary iteration, use:
for k, v in dictionary.items():
- Dictionaries are often used to count elements:
votes = [...] dict_results = {} for vote in votes: if vote not in dict_results: dict_results[vote] = 0 dict_results[vote] += 1 - The syntax above can be simplified to:
votes = [...] dict_results = {} for vote in votes: dict_results[vote] += dict_results.get(vote, 0) + 1 - Dictionaries are also used to group elements by a given characteristic, for instance:
names = [...] groups_dict = {} for name in names: key = len(name) if key not in groups_dict: groups_dict[key] = [] groups_dict[key].append(name) - You can update the values in a dictionary based on another dictionary using:
dict_1.update(dict_2)
Great! Are you ready for the quiz?
Exercise
Click to continue.



