SmithLogo

CSC 111

Introduction to Computer Science Through Programming

Smith Computer Science



Lecture Notes 19: Enumerate, Tuples, and Dictionaries





Iterating over a List: Using enumerate

With lists, we mentioned a couple of ways of going over the contents:



Sometimes having the index is useful, sometimes you don't need it.

There is one last way: using enumerate!



enumerate

Rather than creating and incrementing a variable "by hand", one can use the function enumerate() to get a counter and the value from the iterable at the same time!

example:

li = ['a', 'b', 'c', 'd', 'e']
for count, value in enumerate(li):
  print(count, value)


enumerate() returns two loop variables that can be printed, used to access or compare values, or anything else.




Tuples

A Tuple is created ike this:

player_tuple = ('Pablo', 'Wizard')
print(player_tuple)


A Tuple is created almost the same way as a list (using parentheses instead of square brackets) and can be accessed with the square bracket syntax:

print(player_tuple[1])


The main difference is that a Tuple is immutable! ... once created it cannot be transformed, it can only be overwritten.




What are Dictionaries?

Dictionaries are like lists but instead of accessing elements by their index, we access them through a key.
You can read about them in the Python 2 API for Dictionaries

Meta Structure for a Dictionary





Example Dictionary: MLB teams by state








Working with Dictionaries

Creating a Dictionary

One can use several approaches to create a dictionary.

The first is to use comma separated Key:value pairs inside a pair of curly brackets ( { ... }).

Example 1: MLB teams by state with {...}

# braces
MLB_team_1 = {
            'Colorado':'Rockies', 
            'Boston': 'Red Sox', 
            'Minnesota': 'Twins', 
            'Milwaukee': 'Brewers', 
            'Seattle': 'Mariners'
            }                                    

print (MLB_team_1)


Another is to use the dict function.

Example 2: MLB teams by state with dict

# list of pairs
MLB_team_2 = dict ([
        ('Colorado', 'Rockies'),
        ('Boston', 'Red Sox'),
        ('Minnesota', 'Twins'),
        ('Milwaukee', 'Brewers'),
        ('Seattle', 'Mariners') 
                  ])

print (MLB_team_2)


And yet a third option is to use the assigned pairs syntax.

Example 3 MLB teams by state with dict

# assigned pairs
MLB_team_3 = dict (
        Colorado = 'Rockies',
        Boston = 'Red Sox',
        Minnesota = 'Twins',
        Milwaukee = 'Brewers',
        Seattle = 'Mariners' 
                  )

print (MLB_team_3)


If all the data is available and it is not a lot, the braces approach might be simplest.

However, if a lot of data needs to be added, the best approach would be to:
  1. create an empty dictionary
  2. add elements as needed


Before we do this, we need to be able to "access" elements in the dictionary:

Accessing a Dictionary

This is pretty simple; you use the square brackets ([ ... ]) syntax,
except instead of indicating the index you want, you specify the desired key!

Example: Printing one of the teams

The following is a way of getting at one of the teams by using the key:

MLB_team_1 = {
            'Colorado':'Rockies', 
            'Boston': 'Red Sox', 
            'Minnesota': 'Twins', 
            'Milwaukee': 'Brewers', 
            'Seattle': 'Mariners'
            }   

print(MLB_team_1['Milwaukee'])


But what if I try to access indices?

Try this:
print (MLB_team_1[1])


What happens?

Creating an Empty Dict and adding elements as needed

One can create an empty dictionary like this:

# empty dictionary
bag = {}


Adding to a Dictionary

You can add elements to a dictionary by making an assignment to a new key:

MLB_team_1['New York'] = 'Mets'

print (MLB_team_1)


Activity 1 [2 minutes]:
Create a dictionary of players that has the following key-value pairs:
  • Pablo - Wizard
  • Yak - Barbarian
  • Mar - Rogue
  • Dan - Priest
(Wait; then Click)

# creation (empty)
players = {}

# adding
players['Pablo'] = 'Wizard'
players['Yak'] = 'Barbarian'
players['Mar'] = 'Rogue'
players['Dan'] = 'Priest'

print (players)




What data can I add?

As Keys, you can use integers, floats, strings, or booleans.

As Values, you can have whatever: integers, strings, lists, other dictionaries!, etc.

Activity 2 [2 minutes]:
Make a gradebook for three imaginary students with grades for four different assignments:
  • Smarty Pants: B-, B+, A-, B
  • Slacky Slacks: C, D+, B-, C
  • Flunky Flunk: E, E, E, E
(Wait; then Click)

What structure could you use?

string keys with lists of grades as values... or
string keys with a dictionary of assignment-grade key-value pairs



One important aspect of "accessing" dictionaries is that (in a similar fashion as the "index out of bounds") error for lists, one can run into trouble if one searches for an nonexistant key:

# creation (empty)
players = {}

# adding
players['Pablo'] = 'Wizard'
players['Yak'] = 'Berzerker'
players['Mar'] = 'Rogue'
players['Dan'] = 'Priest'

print (players)

print (players['Shinyoung'])


We will deal with this elegantly later on.




Dictionary Methods

The following table shows a sumary of common methods for dictionaries:



In particular, look at the get method.

It allows you to deal with nonexistent keys. Later, we'll see another way of dealing with these types of runtime exceptions.




Iterating in Dictionaries

In dictionaries, we don't have indices, so we use the second approach:

players = {}
players['Pablo'] = 'Wizard'
players['Yak'] = 'Berzerker'
players['Mar'] = 'Rogue'
players['Dan'] = 'Priest'

for player in players:
  print(player)


Views

Views, or view objects, are (read-only) iterable containers that allow you to go over all or parts of a dictionary.
(iterable is any object that can return its members one at a time.)

Examples



players = {}
players['Pablo'] = 'Wizard'
players['Yak'] = 'Berzerker'
players['Mar'] = 'Rogue'
players['Dan'] = 'Priest'

# items view
print("### items view ###")
p_items = players.items()
for player, role in p_items:
  print ("player {} is a {}".format(player, role))

print()
  
# keys view
print("### keys view ###")
p_keys = players.keys()
for player in p_keys:
  print ("one player is {}".format(player))

print()

# values view
print("### values view ###")
p_values = players.values()
for role in p_values:
  print ("one role is {}".format(role))


Converting into lists

Sometimes, we might want to have a "list" version of a part of a dictionary:

players = {}
players['Pablo'] = 'Wizard'
players['Yak'] = 'Berzerker'
players['Mar'] = 'Rogue'
players['Dan'] = 'Priest'
# converting to list
pk_list = list(players.keys())
# sorting that list
sorted_pk_list = sorted(pk_list)

print(sorted_pk_list)


Note that if you make the "items" view of a Dictionary into a list, you generate a list of tuples.

players = {}
players['Pablo'] = 'Wizard'
players['Yak'] = 'Berzerker'
players['Mar'] = 'Rogue'
players['Dan'] = 'Priest'
# converting to list
pi_list = list(players.items())
# sorting that list
sorted_pi_list = sorted(pi_list)

print(sorted_pi_list)


This allows us to work with the list as when we use enumerate:

players = {}
players['Pablo'] = 'Wizard'
players['Yak'] = 'Berzerker'
players['Mar'] = 'Rogue'
players['Dan'] = 'Priest'
# converting to list
pi_list = list(players.items())
# sorting that list
sorted_pi_list = sorted(pi_list)

print(sorted_pi_list)

for key, value in pi_list:
  print ("player {} is a {}".format(key, value))




Also, check what happens if you convert the dictionary into a list directly:

players = {}
players['Pablo'] = 'Wizard'
players['Yak'] = 'Berzerker'
players['Mar'] = 'Rogue'
players['Dan'] = 'Priest'
# converting to list
p_list = list(players)
# sorting that list
sorted_p_list = sorted(p_list)

print(sorted_p_list)




Additional readings

Check out this article on working with Dictionaries
Also, check this article on enumerate




Homework

[Due for everyone]
Today: submit your project proposals to the link indicated in Moodle.
Remember, you must submit today but we can still discuss the final project (these are only deas, not contracts)
Homework 06 is Due Today (with auto extension to 03/21)

[Optional]