Skip to content

Dictionaries

A dictionary is like a list, but more general, In a list, the index positions have to be integers, in a dictionary, the indices can be (almost) any type.

A dictionary is a mapping between a set of indices (which are called keys) and a set of values. Each key maps to a value. The association of a key and value is called a key-value pair or an item. A key can be any immutable Python object.

Dictionaries are created using curly braces { } or the dict() function.

As a first example we create an english to french dictionary.

eng2fren = {'one':'une', 'two':'deux'}
eng2fren['two']
Output:
deux

We can add a new key-value pair to the dictionary:

eng2fren['three']= 'trois'
print(eng2fren.keys())
print(eng2fren.values())
print(eng2fren.items())
Output:
dict_keys(['one', 'two', 'three'])
dict_values(['une', 'deux', 'trois'])
dict_items([('one', 'une'), ('two', 'deux'), ('three', 'trois')])

Each of these can be turned into lists using the list() command.

The in operator is used to check if a given KEY exist in a dictionary's set of keys.

print('one' in d)        
print('une' in d)      # une is a value, not a key
# convert a tuple to a dictionary:
x = (("A",1),("B",2))
print(dict(x))
Output:
True
False
{'A': 1, 'B': 2}

We can loop through the keys in a list:

for key in eng2fren:
    print(item,val)
Output:
one
two
three

We can also loop through the key-value pairs.

for key,val in eng2fren.items():
    print(key,val)
Output:
one une
two deux
three tois

Other Dictionary Operations

Dictionaries are mutable so we can add and remove entries.

d = {'A':1,'B':2,'C':3}
d['D']=5     # add an entry
del d['A']   # remove an entry
print(d.pop('C'))   # remove an entry *and return its value*
print(d)
Output:
3
{'B': 2, 'D': 5}

Updating a dictionary add the entries from one dictionary to another.

d2 = {"F":5, "G":7, "H":10}
d.update(d2)
print(d)
Output:
{'B': 2, 'D': 5, 'F': 5, 'G': 7, 'H': 10}

Dictionary Inversion

Sometimes you might want to invert a dictionary: swap the key-value pairs. If we have a simple dictionary with a one-to-one match between keys and values then invert as follows:

inv = {}         # initialize an empty dictionary
for k in d:      # loop over keys
   inv[d[k]] = k # add d[k] as a key with k as its value

This can also be done as follows.

inv = {}
for k,v in d.items():
   inv[v] = k

We now consider inversion of a dictionary in which two different keys may have the same value. In this case the inversion would need to associate a list to each key in the inverted dictionary.

For example, suppose number_to_grades is a dictionary with keys consisting of students numbers and values the (letter) grades for each student in the course. The inverted version of this dictionary could be called grades_to_numbers and would have the set of (letter) grades as its keys and student numbers as its values. In the original dictionary, each student number has a single grade associated with it. In the inverted dictionary, there may be several students having the same grade. The values for the inverted dictionary would naturally be a list or a set.

The file grade_file.txt contains a list of student numbers and letter grades for each student. First we create a dictionary called numbers_to_grade from this file that has the student numbers as keys and the grades as values.

grades_file = open('grade_file.txt')
number_to_grades = {}        # initialize the dict
for line in grades_file:     # for each line, add the pair
    number, grade = tuple(line.split())
    number_to_grades[number] = grade
grades_file.close()    

Now we invert the dictionary to create a dictionary called grades_to_numbers.

grades_to_numbers = {}       # intialize the inverted dict
for number, grade in number_to_grades.items():
    if grade in grades_to_numbers:     # old key
        grades_to_numbers[grade].append(number)
    else:     # new key, so add it (as a one-element list) to the dict
        grades_to_numbers[grade] = [number]

Using dictionaries to count frequencies

Suppose you are given a string and you want to count how many times each letter appears. An advantage of a dictionary implementation is that we don't need to know ahead of time which letters appear in the string, we only have to make room for the letters that do appear.

word = 'mathematics'
d = dict()
for c in word:
    if c not in d:
        d[c] = 1
    else:
        d[c] += 1
print(d)                
Output:
{'m': 2, 'a': 2, 't': 2, 'h': 1, 'e': 1, 'i': 1, 'c': 1, 's': 1}

The .get(key,default_value) method of a dictionary returns the value for key if key is in the dictionary, otherwise it returns the default_value. This allows us to simplify the above code as follows.

word = 'mathematics'
d = dict()
for c in word:
    d[c] = d.get(c,0) + 1
print(d)                

Look at the Examples section where we write a word frequencey counter using this idea.