## 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:

names="Martin Luther King".split(" ")
names[1]


‘Luther’

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

me = { "name": "James", "age": 39, "Jobs": ["Programmer", "Teacher"] }

print(me)


{‘name’: ‘James’, ‘age’: 39, ‘Jobs’: [‘Programmer’, ‘Teacher’]}

print(me['Jobs'])


[‘Programmer’, ‘Teacher’]

print(type(me))


<class ‘dict’>

### Keys and Values

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

me.keys()


dict_keys([‘name’, ‘age’, ‘Jobs’])

The things we can look up are called values:

me.values()


dict_values([‘James’, 39, [‘Programmer’ , ‘Teacher’]])

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

'Jobs' in me


True

For values this needs to be done differently

'James' in me


False

'James' in me.values()


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.

good_match = {("Lamb", "Mint"): True, ("Bacon", "Chocolate"): False}


but:

illegal = {[1,2]: 3}


—————————————————————————

TypeError Traceback (most recent call last)

<ipython-input-12-cca03b227ff4> in () </span>

—-> 1 illegal = {[1,2]: 3}

TypeError: unhashable type: ‘list’

Supplementary material: You can start to learn about the ‘hash table’ in this YouTube Video

This material is very advanced, but, I think, really interesting!

### No guarantee of order

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

my_dict = {'0': 0, '1':1, '2': 2, '3': 3, '4': 4}
print(my_dict)
print(my_dict.values())


{‘4’: 4, ‘0’: 0, ‘1’: 1, ‘2’: 2, ‘3’: 3}

dict_values([4, 0, 1, 2, 3])

### Sets

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

name = "James Hetherington"
unique_letters = set(name)

unique_letters


{‘ ‘, ‘H’, ‘J’, ‘a’, ‘e’, ‘g’, ‘h’, ‘i’, ‘m’, ‘n’, ‘o’, ‘r’, ‘s’, ‘t’}

print("".join(unique_letters))


mth sareJHngoi

To see more clearly how join works:

"".join(['a', 'b', 'c'])


‘abc’

Similarly to a dictionary, a set has no particular order for the elements it contains. It is really useful for checking or storing unique values.

alist = [1, 2, 3]
is_unique = len(set(alist)) == len(alist)
print(is_unique)


True

### Safe Lookup

If we have a dictionary, x

x = {'a':1, 'b':2}


We can access the value associated with a key

x['a']


1

However, if the key does not exist an error is generated.

x['fish']


—————————————————————————

KeyError Traceback (most recent call last)

<ipython-input-21-81af752ce649> in <module>()

—-> 1 x[‘fish’]

KeyError: ‘fish’

Using the get() method, we can access the value via the key

x.get('a')


1

x.get('fish')


If the key is not available the default value None will be returned.

print(x.get('fish'))


None

Alternatively, we can define the value to be returned.

x.get('fish', 'tuna') == 'tuna'


True

In this example, the default value for key fish is tuna.