Skip to main content

8.6) Dictionaries


Dictionaries are collections of items, like lists and tuples, but unordered. The elements are referenced by keys instead of position/index. We say that a dictionary is a mapping and a list or tuple is a sequence.

Here’s the syntax to define a dictionary:

D = {<key_a>:<value_a>, < key_b>:<value_b>, < key_c>:<value_c>, ...}

Dictionaries are delimited by curly brackets {}, notice the colon in between the key and value pairs and the pairs of key-value are separated by commas.

  • Keys are usually integers and/or strings, but they can be anything that can be named and uniquely sorted, so it could be a list or tuple for example. Keys can be of different types within the same dictionary
  • Values can be any kind of object, number, sequence or even a function. As with lists and tuples, dictionaries can contain a mix of values of different types

Let’s show a simple example:

mydict = {'var1':1, 'var2':'abc', 'var3':(1,2,3)}

This dictionary has three keys: 'var1', 'var2' and 'var3'. the key 'var1' is associated with the value 1, the key 'var2' is associated with the value 'abc' and the key 'var3' is associated with the value (1,2,3).