Dictionaries#

Introduction to Dictionaries#

Python offers several collection types, including lists and tuples. The dictionary (dict) is another powerful collection type that consists of key-value pairs. This structure is analogous to a traditional dictionary, where words (keys) have corresponding definitions (values).

A dictionary entry for the word Python.

Defining a Dictionary#

Dictionaries are defined using curly braces {}, with key–value pairs separated by colons :.

chlorine = {
    'chemical symbol': 'Cl', 
    'atomic number': 17, 
    'average mass number': 35.45, 
    'x-ray scattering length': 2.76+0.05j
}

print(chlorine)
{'chemical symbol': 'Cl', 'atomic number': 17, 'average mass number': 35.45, 'x-ray scattering length': (2.76+0.05j)}

Here, we are able to use the keys of the dictionaries as labels for each datum.

Accessing Dictionary Elements#

Accessing Keys#

You can get all keys in a dictionary using the keys() method:

print(chlorine.keys())
dict_keys(['chemical symbol', 'atomic number', 'average mass number', 'x-ray scattering length'])

It is possible to access a single one of the elements of a dictionary, by passing the relevant key in lieu of an index.

Accessing Values#

To access a single element, you can use the corresponding key as an index:

chlorine['atomic number']
17

Modifying Dictionaries#

Dictionaries are mutable (you can change them after they have been created), allowing you to add or modify key–value pairs.

Adding New Key–Value Pairs#

chlorine['number of isotopes'] = 2

print(chlorine)
{'chemical symbol': 'Cl', 'atomic number': 17, 'average mass number': 35.45, 'x-ray scattering length': (2.76+0.05j), 'number of isotopes': 2}

Removing Key–Value Pairs#

We can remove key–value pairs from a dictionary using the pop() method:

removed_value = chlorine.pop('number of isotopes')
print(f"Removed value: {removed_value}")
print(chlorine)  # The 'number of isotopes' key-value pair is now removed
Removed value: 2
{'chemical symbol': 'Cl', 'atomic number': 17, 'average mass number': 35.45, 'x-ray scattering length': (2.76+0.05j)}

Modifying Existing Values#

chlorine['atomic number'] = 18  # This would be incorrect, but demonstrates modification
print(chlorine['atomic number'])
18

Dictionary Values#

Dictionary values can be of any type, including other collections like lists or tuples:

chlorine['mass numbers'] = (35, 37)
print(chlorine)
{'chemical symbol': 'Cl', 'atomic number': 18, 'average mass number': 35.45, 'x-ray scattering length': (2.76+0.05j), 'mass numbers': (35, 37)}
## Additional Dictionary Operations

### Checking for Key Existence

print('atomic number' in chlorine)  # Output: True
print('melting point' in chlorine)  # Output: False
True
False

Getting Values Safely#

A dictionary can only be indexed using its existing keys, and if we try to access a dictionary value with an invalid key, we get a KeyError:

chlorine['colour']
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
Cell In[9], line 1
----> 1 chlorine['colour']

KeyError: 'colour'

We might have code where we do not know in advance whether a dictionary will have a particular key–value pair, but do not want our code to break if this pair is absent. We can achieve this using the get() method, which returns the appropriate value or None is our dictionary does not have the key provided.

print(chlorine.get('atomic number'))
print(chlorine.get('melting point'))

When to Use Dictionaries#

  1. When you need a logical association between a key:value pair.

  2. When you need fast lookup for your data, based on a custom key.

  3. When your data is being constantly modified. Remember, dictionaries are mutable.

Dictionaries vs. Lists#

  1. Accessing Elements: List elements are accessed by index (integer-based). Dictionary elements are accessed by keys (which can be of various immutable types, not just integers).

  2. Purpose: Lists are best for collections of similar items where order matters and you need integer-based indexing. Dictionaries are ideal for key-value associations and when you need fast lookup based on a unique key.

Exercise#

Create a dictionary where the keys are the names of the first-row of transition metals, and the values are integers of the number of valence electrons. Test your dictionary by printing some of the values.