Python: Dictionaries

A dictionary is similar to a list, but you access values by looking up a keyinstead of an index. A key can be any string or number. Dictionaries are enclosed in curly braces, like so:

d = {'key1' : 1, 'key2' : 2, 'key3' : 3}
This is a dictionary called d with threekey-value pairs. The key 'key1'points to the value 1'key2' to 2, and so on.

Like Lists, Dictionaries are “mutable”. This means they can be changed after they are created. One advantage of this is that we can add new key/value pairs to the dictionary after it is created like so:

dict_name[new_key] = new_value

An empty pair of curly braces {} is an empty dictionary, just like an empty pair of [] is an empty list.

Because dictionaries are mutable, they can be changed in many ways. Items can be removed from a dictionary with the del command:

del dict_name[key_name]
A dictionary’s keys MUST be both immutable and hashable. Don’t worry if you don’t understand what that means