d = {'hello': 'A greeting'}
d['hello']
'A greeting'
Here 'hello' is called the key and 'A greeting' is the value.
k = {'hello': 'A greeting', 1: 'One'}
k[1]
'One'
Note that now the key is a number and the value is a string.
y = {1: 2, 3: 4}
y[1] = y[1] + 1
y[1]
3
## Construct a dictionary that maps three words to three sentences
oxford = {...}
my_dict = {'hello': 'world'}
... ## look up 'hello', should return 'world'
## Construct a dictionary that maps three numbers to three words
number_map = {...}
concept_map = {...}
concept_map['donkey'] ## should return "is an animal"
histogram = {'a': 5, 'b': 7, 'd': 9}
... # increase the count of 'b' by 2
histogram['b'] # should yield 9
# Advanced challenge: use the histogram above, and generate a list
# containing the corresponding items.
#
# E.g., histogram = {'a': 3, 'b': 2} => ['a', 'a', 'a', 'b', 'b']
# histogram = {'a': 1, 'd': 4} => ['a', 'd', 'd', 'd', 'd']
output = []
for key in histogram:
...
When trying to break simple ciphers (e.g., http://en.wikipedia.org/wiki/Substitution_cipher) it is often useful to count the number of times each letter occurs in a piece of text. In the following example, we count such occurrences and plot them.
text = """
Hereupon Legrand arose, with a grave and stately air, and brought me the beetle
from a glass case in which it was enclosed. It was a beautiful scarabaeus, and, at
that time, unknown to naturalists—of course a great prize in a scientific point
of view. There were two round black spots near one extremity of the back, and a
long one near the other. The scales were exceedingly hard and glossy, with all the
appearance of burnished gold. The weight of the insect was very remarkable, and,
taking all things into consideration, I could hardly blame Jupiter for his opinion
respecting it."""
frequency = {}
alphabet = 'abcdefghijklmnopqrstuvwxyz'
for l in alphabet:
frequency[l] = 0
for l in text.lower():
if l and l in alphabet:
frequency[l] += 1
print frequency
{'a': 48, 'c': 16, 'b': 9, 'e': 58, 'd': 16, 'g': 13, 'f': 9, 'i': 34, 'h': 22, 'k': 5, 'j': 1, 'm': 6, 'l': 21, 'o': 30, 'n': 35, 'q': 0, 'p': 9, 's': 27, 'r': 31, 'u': 12, 't': 41, 'w': 12, 'v': 3, 'y': 6, 'x': 2, 'z': 1}
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(26)
f = [frequency[alphabet[l]] for l in x]
plt.stem(x, f)
plt.xticks(x, alphabet);
Now, have a look at this Morse code table. Is there any correlation between the length of each code and the table above?