1.7. Introducing dictionaries

A short digression is in order, because you need to know about dictionaries, tuples, and lists (oh my!). If you’re a Perl
hacker, you can probably skim the bits about dictionaries and lists, but you should still pay attention to tuples.

One of Python’s built-in datatypes is the dictionary, which defines one-to-one relationships between keys and values.

A dictionary in Python is like a hash in Perl. In Perl, variables which store hashes always start with a % character; in Python, variables can be named anything, and Python keeps track of the datatype internally.

A dictionary in Python is like an instance of the Hashtable class in Java.

A dictionary in Python is like an instance of the Scripting.Dictionary object in Visual Basic.

You can not have duplicate keys in a dictionary. Assigning a value to an existing key will wipe out the old value.

You can add new key-value pairs at any time. This syntax is identical to modifying existing values. (Yes, this will annoy
you someday when you think you are adding new values but are actually just modifying the same value over and over because
your key isn’t changing the way you think it is.)

Note that the new element (key 'uid', value 'sa') appears to be in the middle. In fact, it was just a coincidence that the elements appeared to be in order in the first
example; it is just as much a coincidence that they appear to be out of order now.

Dictionaries have no concept of order among elements. It is incorrect to say that the elements are “out of order”; they are
simply unordered. This is an important distinction which will annoy you when you want to access the elements of a dictionary
in a specific, repeatable order (like alphabetical order by key). There are ways of doing this, they’re just not built into
the dictionary.

Dictionaries aren’t just for strings. Dictionary values can be any datatype, including strings, integers, objects, or even
other dictionaries. And within a single dictionary, the values don’t all have to be the same type; you can mix and match
as needed.

Dictionary keys are more restricted, but they can be strings, integers, and a few other types (more on this later). You can
also mix and match key datatypes within a dictionary.

Example 1.14. Strings are case-sensitive

Assigning a value to an existing dictionary key simply replaces the old value with a new one.

This is not assigning a value to an existing dictionary key, because strings in Python are case-sensitive, so 'key' is not the same as 'Key'. This creates a new key/value pair in the dictionary; it may look similar to you, but as far as Python is concerned, it’s
completely different.