2018-05-15

posted May 15, 2018, 6:20 AM by Konstantinovich Samuel   [ updated May 15, 2018, 6:32 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'}

We can store things using any immutable type as the key (like a non-numerical index).


 
get a value:
dictionary[<ExistingKey]

d2 = {'3': 5, 3: 4, 'bob': 'builder', 'abby': 'host'}
d2[3] #evaluates to 4
print d2[3] #prints 4 to the terminal
d2['3'] #evaluates to 5
d2['abby'] #evaluates to 'host'

change an old value:
dictionary[<ExistingKey>] = <newValue>

d2 = {'3': 5, 3: 4, 'bob': 'builder', 'abby': 'host'}

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 new item:
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:
#5
#14
#dancing queen
#builder
#boss

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


Activity: [complete at home, you will submit on coding bat]
1. Write a function that takes a string and returns a dictionary:
makeDictFromCSV(s)

that takes a string:
"""a,3
b,4
c,6
d,10
f,9
a,99
b,0"""
And adds each row to a dictionary:
The first element is the key, the 2nd element of the row is a value
so if a line is "a,3"
you would say:
d['a']='3'
 
If a key is listed twice, the earlier ones are over-written with new values (in the example above, 'a':'99' takes priority over 'a':'3'

input = """a,3
b,4
c,6
d,10
f,9
a,99
b,0"""

d = makeDictFromCSV(input)

d would be:
{'a': '99', 'f': '9', 'b': '0', 'd': '10', 'c':'6'}



2. 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',
        '2','oNe','3','3','ONe','uno','3'])
would return: 
{'one': 1, 'two': 2, 'ONE': 1, '1': 1, '3': 3, '2': 2, 
 'ONe': 1, 'oNe': 1, 'uno': 1}
Comments