Deals Of The Week - hours only!Up to 80% off on all courses and bundles.-Close
Recap
Counting with dictionaries
Grouping with dictionaries
10. Grouping with dictionaries
Summary

## Instruction

Excellent! Another frequent application of dictionaries is element grouping. Take a look:

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

groups = {}
for name in names:
key = len(name)
if key not in groups:
groups[key] = []
groups[key].append(name)

print(groups)

Result:

{4: ['John', 'Mary', 'Kate', 'Gray'], 5: ['Alice'], 7: ['Michael'], 8: ['Samantha'], 6: ['Adrian']}

In the example above, we have a list of names (the names variable) and we want to group them based on name length. To that end, we create an empty dictionary (groups). The keys in this dictionary are the various name lengths, and the values are lists of matching names. Inside our for loop, we check each name's length. If the length is not an existing key in the dictionary, we create such a key and initialize it with an empty list. Then we append the given name to a given key represented as the name's length.

## Exercise

You are given a list of tuples storing information about airports. Each tuple consists of the airport's name and its number of runways.

Your task is to create a dictionary named runways which will group all airport names by the number of runways. In other words, the keys should represent the numbers of runways and the values should store lists of airport names.

### Stuck? Here's a hint!

Create a for loop and unpack the current tuple into two variables. The rest of the task is very similar to what you see in the explanation.