2017-05-03 HW

posted May 3, 2017, 6:57 AM by Samuel Konstantinovich   [ updated May 3, 2017, 6:58 AM ]
Goal Dictionaries:

Similar to a list, a dictionary is a structure to store information. 
The difference is that it is not stored by index; instead, it stores key:value pairs also known as items.
The key is like the index, and dictionaries use :
   dictionary[key]  instead of list[index]

#empty dictionary
d  = {}  

#dictionary with 4 key:value pairs
d2 = {'3': 5, 3: 4, 'bob': 'builder', 'abby': 'host'}

In a nutshell, we can store things using anything as the index. We call these elements keys.
get a value:

d2[3] #evaluates to 4
print d2[3] #prints 4 to the terminal
d2['3'] #evaluates to 5
d2['abby'] #evaluates to 'host'

change a value:
dictionary[<ExistingKey>] = <newValue>

d2['abby'] = 'boss'   #this replaces 'host' with 'boss'
d2[3] = d2[3] + 10 #add 10 to the value of d2[3]
print d2 
#would show {'3': 5, 3: 14, 'bob': 'builder', 'abby': 'boss'}

add a value:
dictionary[<newKey>] = <newValue>

d2['abba'] = 'dancing queen'
print d2 
#would show:
#{'3': 5, 3: 14, 'abba': 'dancing queen', 'bob': 'builder', 'abby': 'boss'}

Get a list of keys:
d2.keys()#evaluates to ['3', 3, 'abba', 'bob', 'abby']

Loop through the whole dictionary:
for key in d2.keys():
   print d2[key]
#this would print:
#dancing queen

Check if a key is in the dictionary:
>>> 5 in d2
>>> 14 in d2
False  (14 is not a key, it is a value!)
>>> 3 in d2
>>> '3' in d2
>>> 'ABBA' in d2

Activity: [complete at home, submit on coding bat when slot is up]
Write a function tally(L)
Given a list L with strings, return a dictionary as follows:
each key is a word from L, and each value is how many times that word occurred in L.

tally( [ 'a', 'b', 'c', 'a', 'fish', 'b', 'a']) 
would return: 
{'a': 3, 'c': 1, 'b': 2, 'fish': 1}

tally( ['one','1','ONE','two','two','2',
would return: 
{'one': 1, 'two': 2, 'ONE': 1, '1': 1, '3': 3, '2': 2, 
 'ONe': 1, 'oNe': 1, 'uno': 1}