Dictionaries

A dictionary is an unordered set of key-value pairs. When you add a key to a dictionary, you must also add a value for that key. (You can always change the value later.) Python dictionaries are optimized for retrieving the value when you know the key, but not the other way around.

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

Creating a dictionary

Creating a dictionary is easy. The syntax is similar to sets, but instead of values, you have key-value pairs. Once you have a dictionary, you can look up values by their key.

Press + to interact
a_dict = {'server': 'db.diveintopython3.org', 'database': 'mysql'} #①
print (a_dict)
#{'server': 'db.diveintopython3.org', 'database': 'mysql'}
print (a_dict['server'] ) #②
#db.diveintopython3.org
print (a_dict['database'] ) #③
#mysql
print (a_dict['db.diveintopython3.org']) #④
#Traceback (most recent call last):
# File "/usercode/__ed_file.py", line 11, in <module>
# print (a_dict['db.diveintopython3.org']) #\u2463
#KeyError: 'db.diveintopython3.org'

① First, you create a new dictionary with two items and assign it to the variable a_dict. Each ...