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)
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'
}
In [ ]:
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.")
In [ ]:
In [ ]:
for fruit in fruit_season:
print("{0} is best in {1} (at least in Virginia)".format(fruit.title(), fruit_season[fruit]))
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()))
In [ ]:
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)))
In [ ]:
Create an acrostic poem generator.
You will create a function that takes a name and generates an acrostic poem
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 [ ]:
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 [ ]: