Contact Us!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.

| Download
Views: 60
Image: ubuntu2004
Kernel: Python 3 (system-wide)

Week 3 part 1 - dictionaries

A list l has entries l[0], l[1], ..., l[len(l)-1] You could think of the list as being like a function l that sends a number i to l[i].

A Python dictionary d is like a more general version of this where the domain doesn't just have to be numbers. Elements of the domain are called keys, and if k is a key we call d[k] the value for that key. If you've programmed in Java or C++ before, a dictionary is similar to what is called a map in those languages.

As an example, suppose we are writing a program to store people's telephone numbers. We can do this with a dictionary where the keys are people's names, and the values are telephone numbers.

You can create an empty dictionary using {}

phoneNumbers = {}

Once you've created a dictionary d you can add a key k with value v by assigning d[k] = v

phoneNumbers["UCL Admissions"] = "020 3370 1215" phoneNumbers["UCL Security"] = "222"

Now phoneNumbers is a dictionary with two keys, whose values you can access as follows:

phoneNumbers["UCL Admissions"]
'020 3370 1215'
phoneNumbers["UCL Security"]
'222'

You can check if a dictionary has a value for a certain key using in...

"UCL Admissions" in phoneNumbers
True
"UCL Maths" in phoneNumbers
False

...which is useful because asking for a key for which no value is set raises a KeyError:

phoneNumbers["UCL Maths"]
--------------------------------------------------------------------------- KeyError Traceback (most recent call last) /tmp/ipykernel_753/4069038686.py in <module> ----> 1 phoneNumbers["UCL Maths"] KeyError: 'UCL Maths'

We've already seen how to add a key, but we can also remove one using del:

del phoneNumbers["UCL Admissions"]

Now that it's removed, asking for phoneNumbers["UCL Admissions"] raises a KeyError

phoneNumbers["UCL Admissions"]
--------------------------------------------------------------------------- KeyError Traceback (most recent call last) /tmp/ipykernel_753/2382284919.py in <module> ----> 1 phoneNumbers["UCL Admissions"] KeyError: 'UCL Admissions'

Other ways to create dictionaries

Instead of starting with an empty dictionary and adding entries like we did above, you can create a new dictionary with some entries already specified like this:

phoneNumbers = {"UCL Security" : "222", "UCL Admissions" : "020 3370 1215"}

You can even do a "dictionary comprehension", like the list comprehensions we met last week.

counter = {i : 0 for i in range(10)}

What do you think the keys and values are in counter? You can find out by calling counter.keys() and counter.values()

counter.keys()
dict_keys([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
counter.values()
dict_values([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])

Looping over a dictionary

It's common to want to do something for every entry in a dictionary. You can use for loops: if d is a dictionary then

for k in d: # loop body

will run the loop body with k set to each of the keys of the dictionary d. For example:

for name in phoneNumbers: print("the number for", name, "is", phoneNumbers[name])
the number for UCL Security is 222 the number for UCL Admissions is 020 3370 1215

Unassessed exercises

Exercise 1

In this exercise you are going to teach Python how to say certain numbers in English.

Create a dictionary unit_words whose keys are 1, 2, ..., 9 such that unit_words[1] = "one", unit_words[2] = "two", and so on.

unit_words = # your code here

Now create a dictionary tens_words whose keys are 2, 3, ..., 9 such that tens_words[2] = "twenty", tens_words[3] = "thirty", and so on.

tens_words={2:"twenty",3:"thirty",4:"forty",5:"fifty",6:"sixty",7:"seventy",8:"eighty",9:"ninety"}

Now use your dictionaries to write a function say(tens, units) which returns a string representing how the number 10 * tens + units is spoken in English. For example, say(4, 2) should be "forty-two", and say(2, 5) should be "twenty-five". You can assume tens >= 2

def say(tens, units): if units != 0: print(tens_words[tens] + "-" + unit_words[units]) else: print(tens_words[tens]) say(4,2) say(9,0)
--------------------------------------------------------------------------- NameError Traceback (most recent call last) /tmp/ipykernel_2293/1665842116.py in <cell line: 6>() 4 else: 5 print(tens_words[tens]) ----> 6 say(4,2) 7 say(9,0) /tmp/ipykernel_2293/1665842116.py in say(tens, units) 1 def say(tens, units): 2 if units != 0: ----> 3 print(tens_words[tens] + "-" + unit_words[units]) 4 else: 5 print(tens_words[tens]) NameError: name 'unit_words' is not defined

Further suggestions:

  • modify say so that it can deal with the numbers 10, 11, ..., 19 as well

  • modify say so that it can deal with all numbers between 0 and 99

  • modify say so that instead of calling say(4, 2), for example, I can instead call say(42)