Maps (Dictionaries)

Maps (also called hashes or dictionaries) are data structures that associate keys with values. They allow ultra fast access to elements through unique keys. In Python they are known as dictionaries.

A dictionary, or map, consists of a collection of key-value pairs. The key is used to access the associated value. Keys must be unique within a dictionary. Values can be repeated.

Diagram of a map


Main operations

  • Add/update: Inserts a key-value pair. If the key existed, its value is replaced.
    dictionary['key'] = 'value'
    
  • Get value: Accesses the value given a key.
    value = dictionary['key']
    
  • Delete: Removes a key-value pair from the dictionary.
    del dictionary['key']
    
  • Traverse: Iterate over the keys, values or pairs of the dictionary.
    for key in dictionary:
      print(key, dictionary[key]) # key, value
    

Creating a dictionary or map

The syntax for creating maps or dictionaries in Python is:

empty_dictionary = {}

person = {
  'name': 'John',
  'age': 25
}

Usage examples

Dictionaries are useful in many cases. Below are some examples.

Objects and mappings

We can model objects and entities with key-value attributes:

product = {
  'name': 'Smartphone',
  'price': 500,
  'brand': 'XYZ'
}

Counts and frequencies

Counting occurrences of elements in sequences:

text = "Hello world world"

frequencies = {}

for word in text.split():
    if word in frequencies:
        frequencies[word] += 1
    else:
        frequencies[word] = 1

print(frequencies)
# {'Hello': 1, 'world': 2}

Storing and accessing data

As a high performance alternative to lists and arrays.


Conclusion

Dictionaries are versatile data structures thanks to their fast access based on unique keys. They have uses in almost all programs, so mastering dictionaries is essential in any language.



Last modified December 8, 2024: Attempt to fix dev environment (95d5e1c)