3.18 Dictionaries

A dictionary is a way of storing data, associating each item in the dictionary with a name. The common example used to conceptualize this is a phone book - each name is associated with a phone number.

We can define a dictionary using the following syntax:

dictionaryName = {<key1> : <value1>, 
                  <key2> : <value2>}

The keys in a dictionary are conventionally a string or an integer. The values can be most data types (lists, integers, floats, etc.).

A simple creation of a dictionary:

codons = {'Phe' : ['UUG'], 
          'Leu' : ['CUC']}
          
print(codons)
## {'Phe': ['UUG'], 'Leu': ['CUC']}

3.18.1 Looking up values

We can look up the values in a dictionary as such:

codons['Phe']
## ['UUG']

We can also do this by storing the key name as a variable:

myKey = 'Phe'
codons[myKey]
## ['UUG']

3.18.2 Adding to a dictionary

We add to a dictionary as such:

<dictionary name>[<key>] = <value> 

If the key already exists, then you will overwrite the existing value:

print(codons['Leu'])
## ['CUC']
codons['Leu'] = ['CUU']
print(codons['Leu'])
## ['CUU']

If the key does not already exist in your dictionary, you will add a new key-value pair:

codons['Ala'] = ['GCC']
print(codons)
## {'Phe': ['UUG'], 'Leu': ['CUU'], 'Ala': ['GCC']}

Likewise, we can use this syntax to modify existing values:

print(codons['Leu'])
## ['CUU']
codons['Leu'].append('CUG')
print(codons['Leu'])
## ['CUU', 'CUG']

This takes the codon value for Leu, which is the list ['CUU']. Then, we append the value 'CUG'.

3.18.3 Looping through dictionaries

We can get the keys of a dictionary using the method: .keys():

for i in codons.keys():
  print(i)
## Phe
## Leu
## Ala

We can do the same for value using .values():

for i in codons.values():
  print(i)
## ['UUG']
## ['CUU', 'CUG']
## ['GCC']

We can use .items() to iterate through the keys and values together:

for key, value in codons.items():
  print(key, value)
## Phe ['UUG']
## Leu ['CUU', 'CUG']
## Ala ['GCC']

Lastly, if we want the data returned by .keys(), .values(), and .items() stored as list, we can do:

dictionary_keys_list = list(codons.keys())
print(dictionary_keys_list)
## ['Phe', 'Leu', 'Ala']