Back-To-School Deals - hours only!Up to 80% off on all courses and bundles.-Close
Recap
Counting with dictionaries
Grouping with dictionaries
11. Using get() with grouping
Linking with dictionaries
Summary

Instruction

Good job! When grouping elements, we can also use the get() function to shorten the code. Check this out:

names = ['John', 'Mary', 'Alice', 'Kate', 'Michael', 'Samantha', 'Adrian', 'Gray']

groups = {}
for name in names:
  key = len(name)
  groups[key] = groups.get(key, []) + [name]

print(groups)

The code above works in the same way as the previous code, but it is much shorter. Instead of checking if a given key exists, we use groups.get(key, []). This code will either return the existing list for the given key or an empty list. Then all we need to do is add a one-element list with the given name ([name]).

Exercise

Rewrite the template code so that it uses the get() function.

Stuck? Here's a hint!

Use the following line of code:

groups[runways] = groups.get(runways, []) + [airport_name]