Dictionaries in Python

  1. An important data type in Python is the dictionary. Where elements of lists, tuples and strings can be accessed by number, dictionaries can be accessed by more general keys, in particular strings, but more generally any immutable type. A dictionary is constructed using this syntax:

    >>> phonebook = { 'john': 123, 'paul': 456, 'george': 789, 'ringo': 0}
    >>> phonebook['george']
    789
    >>> phonebook['george'] = 999
    >>> phonebook
    {'ringo': 0, 'paul': 456, 'john': 123, 'george': 999}
    

    Like sets, note how the order in which the pairs is presented may not be the order of input. In fact a dictionary is a set of key/value pairs.

  2. We can also get a list of the keys or the values or check whether a key is present in a dictionary:

    >>> phonebook.keys()
    ['ringo', 'paul', 'john', 'george']
    >>> phonebook.values()
    [0, 456, 123, 999]
    >>> 'john' in phonebook
    True
    >>> 'elvis' in phonebook
    False
    
  3. We can iterate over a dictionary:

    >>> for name in phonebook:
    ...   print(name, phonebook[name])
    ...
    ringo 0
    paul 456
    john 123
    george 999
    
  4. Dictionaries work well together with Python's string formatting tools.

Author: Breanndán Ó Nualláin <o@uva.nl>

Date: 2025-02-10 Mon 14:45