Dictionaries

A dictionary is a data type used to map a key to a value.

Access

# This is probably the best place to start with dictionaries.

# First, let's create a string, a list, and a dictionary.

name = "Shannon"

attendees = ['Shannon', 'Amy', 'Jen', 'Julie']

contacts = {
    'Shannon': '202-555-1234',
    'Amy': '410-515-3000',
    'Jen': '301-600-5555',
    'Julie': '202-333-9876'
}

# We can access part of a string using slicing:
print (name[0]) # S

# We can access part of a list using slicing:
print (attendees[0:2]) # Shannon, Amy

# We can access part of a dictionary if we know its key.
print (contacts['Jen']) # 301-600-5555

# In lines 9-14, we created a dictionary.
# Dictionaries are another way of storing information in Python.
# Dictionaries are made up of key+value pairs.

# In the dictionary contacts, the keys are Shannon, Amy, Jen, and Julie.
# A dictionary's keys are strings that you can use to see the contents.
# A dictionary's values can be any type of information - a string, a list, a number, even a dictionary!
# That value is tied to the key - it belongs to a key.

# The best way to think about a dictionary is a phone book or a contact list.
# How difficult would it be if we had to store contacts like this?

contacts_as_list = [
    ['Shannon', '202-555-1234'],
    ['Amy', '410-515-3000'],
    ['Jen', '301-600-5555'],
    ['Julie', '202-333-9876']
]

# What if we wanted to get Jen's phone number? It would be a pain to retrieve it!
# We'd have to loop through each item in the list and check the name, like this:

phone_we_want = 'Jen'

for contact in contacts_as_list:
    if contact[0] == phone_we_want:
        print (contact[1]) # The phone number

# Kind of a pain.  Luckily, dictionaries mean we don't have to do this!

print (contacts['Jen'])

Get data

Read the following example. It is used for getting data from a dictionary. When you are asked to write a name, write a name from the contacts dictionary, otherwise you will get an error. You will learn how to deal with errors later in this python course.

# We create a dictionary.

contacts = {
    'Shannon': '202-555-1234',
    'Amy': '410-515-3000',
    'Jen': '301-600-5555',
    'Julie': '202-333-9876'
}

name = input("Enter the name of the person whose phone number you want: ")

print ("We will get a KeyError if you entered a name that wasn't in the dictionary.")
print ("{0}'s number is: {1}".format(name, contacts[name]))

print ("But there's a way we don't need to worry about KeyErrors.")

name = input("Enter the name of the person whose phone number you want ... might I suggest Frankenstein? ")

# .get() is a dictionary method that lets us safely access a dictionary even if that key doesn't exist.

print ("{0}'s number is ... {1}".format(name, contacts.get(name, " ... I couldn't find it!")))

Items, keys and values

Items

# We create a dictionary.

contacts = {
    'Shannon': '202-555-1234',
    'Amy': '410-515-3000',
    'Jen': '301-600-5555',
    'Julie': '202-333-9876'
}

# We can use the dictionary method .items() to give us a list of all of the items in contacts.

print( contacts.items())

# Strictly speaking, .items() doesn't give us a list, it gives us a *tuple*, which is another way of storing information in Python.
# Tuples are almost identical to lists, except they're read-only.  You can't add to/remove from a tuple.
# But they're accessed and used in pretty much the same way, so we're going to treat it as if Python's giving us a list, and it will behave as we expect.

# .items() gives us a key and value pair together - so we can use that directly when we're looping.

for contact, phone in contacts.items():
    print ("{0}'s number is {1}".format(contact, phone))

# .items() is probably most commonly used out of .keys(), .values(), and .items() because it gives you both the key and the value together.

Keys

We start as in the previous example.

# We create a dictionary.

contacts = {
    'Shannon': '202-555-1234',
    'Amy': '410-515-3000',
    'Jen': '301-600-5555',
    'Julie': '202-333-9876'
}

# We can use the dictionary method .keys() to give us a list of all of the keys in contacts.

print (contacts.keys())

for contact in contacts.keys():
    print ("{0}'s number is {1}".format(contact, contacts[contact]))

# Dictionaries are unordered, so the keys (and their values) might be in a different order each time.  Or they might not.  Either way, that's normal.

# In other words, you can't rely on the ordering of anything in a dictionary.  But you could apply ordering to the keys.

# The built-in function sorted() will sort a list in ascending order.

for contact in sorted(contacts.keys()):
    print ("{0}'s number is {1}".format(contact, contacts[contact]))

Values

contacts = {
    'Shannon': '202-555-1234',
    'Amy': '410-515-3000',
    'Jen': '301-600-5555',
    'Julie': '202-333-9876'
}

# We can use the dictionary method .values() to give us a list of all of the values in contacts.

print (contacts.values())

for phone in contacts.values():
    print ("{0}".format(phone))

# .values() is used less frequently than .keys() since you can't get the key from the value (but you can get the value if you know the key)

# Use .values() when you don't care what the key is, you just want a list of all of the values.  It's less common, but still good to know.

Update

contacts = {
    'Shannon': '202-555-1234',
    'Amy': '410-515-3000',
    'Jen': '301-600-5555',
    'Julie': '202-333-9876'
}

# If we want to add a new item to a dictionary, we can use direct access to change it.
contacts['Rachel'] = '202-888-1234'

# We can do the same thing to change an existing dictionary item, too.
contacts['Amy'] = '703-444-8888'

# That's great for changing a dictionary one key at a time, but let's say we have a lot of updates.  We have two options.

new_contacts = {
    'Kristin': '703-333-1234',
    'Katie': '301-555-9876',
    'Grace': '202-777-2222',
    'Charlotte': '410-555-9999'
}

# Option 1: Loop through the changes one at a time.

for name, phone in new_contacts.items():
    contacts[name] = phone

# Now contacts has everything in new_contacts.
print (contacts, "\n")


# Let's set contacts back to the value it had before we added new_contacts.

contacts = {
    'Shannon': '202-555-1234',
    'Amy': '410-515-3000',
    'Jen': '301-600-5555',
    'Julie': '202-333-9876',
    'Rachel': '202-888-1234'
}

# Option 2: Use the dictionary method .update()

contacts.update(new_contacts)

print (contacts)

License