XClose

An introduction to research programming with Python

Home
Menu

Dictionaries

The Python Dictionary

Python supports a container type called a dictionary.

This is also known as an "associative array", "map" or "hash" in other languages.

In a list, we use a number to look up an element:

In [1]:
names = "Martin Luther King".split(" ")
names[1]
Out[1]:
'Luther'

In a dictionary, we look up an element using another object of our choice:

In [2]:
me = {"name": "James", "age": 39, "Jobs": ["Programmer", "Teacher"]}
In [3]:
print(me)
{'name': 'James', 'age': 39, 'Jobs': ['Programmer', 'Teacher']}
In [4]:
print(me["Jobs"])
['Programmer', 'Teacher']
In [5]:
print(type(me))
<class 'dict'>

Keys and Values

The things we can use to look up with are called keys:

In [6]:
me.keys()
Out[6]:
dict_keys(['name', 'age', 'Jobs'])

The things we can look up are called values:

In [7]:
me.values()
Out[7]:
dict_values(['James', 39, ['Programmer', 'Teacher']])

When we test for containment on a dict we test on the keys:

In [8]:
"Jobs" in me
Out[8]:
True
In [9]:
"James" in me
Out[9]:
False
In [10]:
"James" in me.values()
Out[10]:
True

Immutable Keys Only

The way in which dictionaries work is one of the coolest things in computer science: the "hash table". This is way beyond the scope of this course, but it has a consequence:

You can only use immutable things as keys.

In [11]:
good_match = {("Lamb", "Mint"): True, ("Bacon", "Chocolate"): False}

but:

In [12]:
illegal = {[1, 2]: 3}
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In [12], line 1
----> 1 illegal = {[1, 2]: 3}

TypeError: unhashable type: 'list'

Supplementary material: You can start to learn about the 'hash table'. Though this video is very advanced I think it's really interesting!

No guarantee of order

Another consequence of the way dictionaries work is that there's no guaranteed order among the elements:

In [13]:
my_dict = {"0": 0, "1": 1, "2": 2, "3": 3, "4": 4}
print(my_dict)
print(my_dict.values())
{'0': 0, '1': 1, '2': 2, '3': 3, '4': 4}
dict_values([0, 1, 2, 3, 4])

Sets

A set is a list which cannot contain the same element twice.

In [14]:
university = "University College London"
unique_letters = set(university)
In [15]:
unique_letters
Out[15]:
{' ',
 'C',
 'L',
 'U',
 'd',
 'e',
 'g',
 'i',
 'l',
 'n',
 'o',
 'r',
 's',
 't',
 'v',
 'y'}
In [16]:
print("".join(unique_letters))
gyvUolsCLtn erdi
In [17]:
"".join(["a", "b", "c"])
Out[17]:
'abc'

It has no particular order, but is really useful for checking or storing unique values.

In [18]:
alist = [1, 2, 3]
is_unique = len(set(alist)) == len(alist)
print(is_unique)
True

Safe Lookup

In [19]:
x = {"a": 1, "b": 2}
In [20]:
x["a"]
Out[20]:
1
In [21]:
x["fish"]
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
Cell In [21], line 1
----> 1 x["fish"]

KeyError: 'fish'
In [22]:
x.get("a")
Out[22]:
1
In [23]:
x.get("fish")
In [24]:
x.get("fish", "tuna") == "tuna"
Out[24]:
True