Dictionaries

A dictionary is datatype that contains a series of key-value pairs. It is similar to a list except for that the indices of the values can be strings, tuples, etc. not just integers. It is also different in that it is unordered. You cannot expect to get the keys in the same order out as you put them in.

To create a dictionary:

my_dict = { key1: value1, key2: value2 }

Creating an empty dictionary

my_dict = {} 
my_dict = dict()

In [ ]:
fruit_season = {
    'raspberry': 'May',
    'apple'    : 'September',
    'peach'    : 'July',
    'grape'    : 'August'
} 

print(type(fruit_season))
print(fruit_season)

To access a value, you index into it similarly to a list using square brackets.

value_of_key1 = my_dict['key1'] 

In [ ]:
raspberry_season = fruit_season['raspberry']
print(raspberry_season)

Trying to access a key not in the dictionary throws an error


In [ ]:
print(fruit_season['mangos'])

To add an item to the dictionary set the value equal to the indexed keys

dict['new_key'] = value

In [ ]:
fruit_season['strawberry'] = 'May'
print(fruit_season)

To delete a key, use the del keyword

del dict['key to delete']

In [ ]:
del fruit_season['strawberry']
print(fruit_season)

Rules on keys

Keys in dictionary must be unique. If you try to make a duplicate key, the data will be overwritten

Keys must be hashable. What this means is they must come from immutable values and be comparable. You can use strings, numbers, tuples, sets, (most) objects. You cannot use lists or dictionaries as keys.


In [ ]:
duplicate_fruit_season = {
    'raspberry': 'May',
    'raspberry': 'June',
} 
print(duplicate_fruit_season)

In [ ]:
mutable_key = {
    ['watermelon', 'cantaloupe', 'honeydew']: 'July'
}

In [ ]:
# The solution is to use a tuple instead
immutable_key = {
    ('watermelon', 'cantelope', 'honeydew'): 'July'
}

TRY IT

Create a dictionary called vegetable_season with Eggplant-> July and Onion -> May


In [ ]:

Dictionary Operators

The in operator returns a boolean for whether the key is in the dictionary or not.

key in dictionary 

In [ ]:
print('raspberry' in fruit_season)
print('mangos' in fruit_season)

You can use this in if statement


In [ ]:
if 'pineapple' in fruit_season:
    print('Lets eat tropical fruit')
else:
    print("Temperate fruit it is.")

TRY IT

Check if 'broccoli' is in vegetable_season. If so, print 'Yum, little trees!'


In [ ]:

Dictionaries and Loops

You can use a for in loop to loop through dictionaries

for key in dictionary:
    print key

In [ ]:
for fruit in fruit_season:
    print("{0} is best in {1} (at least in Virginia)".format(fruit.title(), fruit_season[fruit]))

Dictionary Methods

You can use the keys, values, or items methods to return lists of keys, values, or key-value tuples respectively.

You can then use these for sorting or for looping


In [ ]:
print(list(fruit_season.keys()))
print(list(fruit_season.values()))
print(list(fruit_season.items()))

In [ ]:
for key, value in list(fruit_season.items()):
    print("In {0} eat a {1}".format(value, key))

In [ ]:
print(sorted(fruit_season.keys()))

TRY IT

Loop through the sorted keys of the vegetable_season dictionary. For each key, print the month it is in season


In [ ]:

More complex dictionaries

Dictionary keys and values can be almost anything. The keys must be hashable which means it cannot change. That means that lists and dictionaries cannot be keys (but strings, tuples, and integers can).

Values can be just about anything, though.


In [ ]:
my_complicated_dictionary = {
    (1, 2, 3): 6,
    'weevil': {
        'e': 2,
        'i': 1,
        'l': 1,
        'v': 1,
        'w': 1,
    },
    9: [3, 3]
}
print(my_complicated_dictionary)

Let's use this to create a more realistic fruit season dictionary


In [ ]:
true_fruit_season = {
    'raspberry': ['May', 'June'],
    'apple': ['September', 'October', 'November', 'December'],
    'peach': ['July', 'August'],
    'grape': ['August', 'September', 'October']
} 

print(true_fruit_season)

In [ ]:
months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']

for month in months:
    print(('It is {0}'.format(month)))
    for fruit, season in list(true_fruit_season.items()):
        if month in season:
            print(("\tEat {0}".format(fruit)))

TRY IT

Add a key to the true_fruit_season for 'watermelons' the season is July, August, and September


In [ ]:

Project: Acrostic

Create an acrostic poem generator.

You will create a function that takes a name and generates an acrostic poem

  1. Create a dictionary that has each of the capital letters as keys and an adjective that start with the letter as the value and store in variable named adjectives. (Reference: http://www.enchantedlearning.com/wordlist/adjectives.shtml)
  2. Create a function called acrostic that takes one parameter name.
  3. In the acrostic function capitalize the name (use the upper method)
  4. For each letter in the name
  5. Get the adjective corresponding to that letter and store in a variable called current_adj
  6. Print out Letter-current_adj

Challenge instead of just one adjective have each letter's value be a list of adjectives. Use the random module to select a random adjective instead of always selecting the same one.


In [ ]:

Bonus Material

Auto generating the dictionary for the acrostic:


In [ ]:
# If you have a list of adjectives
my_dict = {}

# Imaging this is the full alphabet
for i in ['A', 'B', 'C']:
    my_dict[i] = []
    
    
for i in ['Adoreable', 'Acceptable', 'Bad', 'Cute', 'Basic', 'Dumb']:
    first_char = i[0]
    if first_char in my_dict:
        my_dict[first_char].append(i)
print(my_dict)

In [ ]:
# Generating from a file
my_dict = {}

for i in ['A', 'B', 'C']:
    my_dict[i] = []
    
# adjectives.txt has one adjective per line
with open('adjectives.txt') as fh:
    for line in fh:
        word = line.rstrip().title()
        first_char = word[0]
        if first_char in my_dict:
            my_dict[first_char].append(word)
            
print(my_dict['A'])

In [ ]: