Dictionaries

How would you store information about which grades you got in which subjects? So far, the only way we saw to store a bunch of information was lists. Maybe you would store things as follows:

subjects =     ["physiology", "anatomy", "infectious disease"]
grades_sub =   ["B+", "A", "A+"]

Then you would access the information by accessing subjects[i] and grades[i], for the same i.

Instead of doing this, you can store the data in a dictionary:

In [1]:
grades = {}  #define an empty dictionary
grades["physiology"] = "B+"   #unlike with lists, this is fine. You can add new entries to the dictionary. (Note that 
                              #you couldn't go L = []; L[5] = "hi")
grades["anatomy"] = "A"   

We can now see what the contents of the dictionary are:

In [2]:
grades
Out[2]:
{'anatomy': 'A', 'physiology': 'B+'}

"anatomy" and "physiology" are called keys, and "A" and "B+" are called values. We can get the values of a dictionry using keys, just like we can get elements of lists using indices.

In [4]:
grades["anatomy"]
Out[4]:
'A'
In [5]:
grades["physiology"]
Out[5]:
'B+'

We can define dictionaries by specifying more than one key-value pair at a time:

In [6]:
my_grades = {'anatomy': 'A', 'physiology': 'B+', 0:10}

Note that keys don't have to be just strings. For example, the third key in the example above is an integer.

Iterating over dictionaries

We can iterate over ditionaties as follows:

In [8]:
for subj in grades:
    print("I got", grades[subj], "in", subj)
I got B+ in physiology
I got A in anatomy

The for-loop puts all the keys in turn (but in no particular order) into subj. That allows us to print out all the information contained in the dictionary.

You can get the keys and values as lists as follows:

In [9]:
list(grades.values())
Out[9]:
['B+', 'A']
In [10]:
list(grades.keys())
Out[10]:
['physiology', 'anatomy']

It possible to iterate over the keys and the values using these constructs:

In [11]:
for grade in grades.values():
    print(grade)    
B+
A
In [12]:
for subj in grades.keys():  #same as simply for subj in grades
    print(subj)    
physiology
anatomy

Finally, you can get the dictionary items as follows:

In [13]:
list(grades.items())
Out[13]:
[('physiology', 'B+'), ('anatomy', 'A')]

The elements of the list above are called tuples. Tuples are the same as lists, except immutable. You can also use .items as follows to iterate over both the keys and the correspond values simoultaneusly:

In [15]:
for subj, grade in grades.items():
    print(subj, grade)  #same as print(subj, grades[subj])
physiology B+
anatomy A