Kickstart 2020 with new opportunities! - hours only!Up to 80% off on all courses and bundles.-Close
Recap
3. Iterating methods – review
Counting with dictionaries
Grouping with dictionaries
Linking with dictionaries
Summary

Instruction

Great! In Python, there are several widely used methods of iterating dictionaries. We'll review them here, in case you've forgotten them.

The tourist_arrivals dictionary contains numbers of tourist arrivals in Croatia in years 2012-2017.

tourist_arrivals = {
  2017: 17430580,
  2016: 15594157,
  2015: 14343323,
  2014: 13128416,
  2013: 12433727,
  2012: 11835160
}

Let's review the iterating techniques for dictionaries. Note that you should never add new elements or delete existing elements when iterating over a dictionary!

  1. We can iterate over the keys:
  2. sum = 0
    for k in tourist_arrivals:
      if k > 2014:
        sum += tourist_arrivals[k]
    
  3. There is an alternative version to the syntax you can use to iterate over dictionary keys. To emphasize that you're iterating over dictionary keys, you can use the keys() method:
    sum = 0
    for k in tourist_arrivals.keys():
      if k > 2014:
        sum += tourist_arrivals[k]
    
    Note that you can still modify the values under specific keys in a dictionary. Both methods we've presented so far will work in this case.
  4. When we don't need the keys, we can simply iterate over the values:
  5. sum = 0
    for v in tourist_arrivals.values():
      sum += v
    print('Total tourist arrivals in Croatia in years 2012-2017:', sum)
    
  6. There are also situations in which we want to get convenient access to both keys and values.
  7. max_year = 0
    max_arrivals = 0
    for k, v in tourist_arrivals.items():
      if v > max_arrivals:
        max_arrivals = v
        max_year = k
    print('The best year in terms of tourist arrivals was', max_year, 'with', max_arrivals, 'arrivals.')
    

Exercise

Here's an exercise for you. Use the iteration method you think is best for this exercise.

Create a function named get_results_range(result_dict) that accepts a dictionary (as shown in the template code) and returns the difference between the best and worst exam results. The results are integers between 0 and 100.

Stuck? Here's a hint!

Start by creating two temporary variables:

max = 0
min = 100

Then, inside a loop, update the values accordingly.