Contents
This notebook is based on "Think Python, 2Ed" by Allen B. Downey
https://greenteapress.com/wp/think-python-2e/
dict
creates a new dictionary object with no items
In [1]:
birthdays = dict()
print( birthdays )
In [2]:
birthdays['0704'] = 'Steve'
birthdays['0529'] = 'Tony'
print( birthdays )
In [3]:
print( birthdays['0529'] )
In [4]:
# Get the number of key-value pairs
print( len( birthdays ) )
# Get the values in the dictionary
print( birthdays.values() )
# Get the keys in the dictionary
print( birthdays.keys() )
In [5]:
for a_date in birthdays:
print( a_date )
In [6]:
def reverse_lookup( a_dict, value ):
for key in a_dict:
if a_dict[key] == value:
return key
raise ValueError
raise
keywordValueError
) if the value isn't in the dictionaryraise
statement also takes an optional argument that is a detailed error message
In [7]:
birthdays['0704'] = [ 'Steve', 'Nick' ]
In [8]:
def invert_dict( a_dict ):
inverted_dict = dict()
for key in a_dict:
value = a_dict[key]
if value not in inverted_dict:
inverted_dict[value] = [ key ]
else:
inverted_dict[value].append( key )
return inverted_dict
__main__
words.txt
exercises, debugging programs that use large amounts of data is difficultwords.txt
file and computes the relative frequency of each letter in the alphabet. For example, if the letter e
occurs 100 times and there are a total of 500 letters in the file, the letter e
has a relative frequency of 20\%.words.txt
file and computes the relative frequency of the length of all the words. You must use a dictionary.