Dictionaries are a powerful tool in Python. A dictionary maps a variable to a set of data,
much like a real dictionary maps a word to its definition, its pronunciation, and its synonyms.
Dictionaries are similar to lists in that they are not homogeneous and can contain objects of any
type. To access an object in a list, you provide the integer index that specifies the position of
the object in the list. For example,
>>> myList = [6,2,9]
>>> myList[1]
2
In contrast, you access an object in a dictionary through its
key, which can be a string, an integer, or any type of immutable
Python object. There is no implicit order to the keys in a dictionary. In most cases you will
assign a string to the dictionary key. The key then becomes a more intuitive way to access the
elements in a dictionary. You use square brackets and the dictionary key to access a particular
object. For
example,
Dictionaries are not sequences, and you cannot apply sequence methods such
as slicing and concatenating to dictionaries. Dictionaries have their own methods. The following
statement lists the methods of the dictionary
myPart.
You use the
in syntax to see if a key exists. A return value of
True indicates the key is a member of the dictionary. A return
value of False indicates the key is not a
member.
>>> 'color' in myPart
1
Python's del statement allows you to delete a
variable.
>>> del myPart
You can also use
del to delete an item from a
dictionary.
>>> del myPart['color']
>>> 'color' in myPart
False
You can use the keys(),
values(), or items() methods to
loop through a dictionary. In the following example, items()
returns two values; the first is assigned to property, and the
second is assigned to
setting.
>>> for property, setting in myPart.items():
... print(property, setting)
...
size 3.0
weight 376.0
number 667
material Steel
cost 10.34