stock = {"FB":(100,101,99,100),
"GOOG":(1000,1001,999,1001)}
>>> stock["FB"]
(100,101,99,100)
>>> stock["RIM"]
KeyError Traceback (most recent call last)
in ()
1 stock = {"FB":(100,101,99,100),
2 "GOOG":(1000,1001,999,1001)}
----> 3 stock["RIM"]
KeyError: 'RIM'
# get() accepts a key as the first parameter and an optional default value if the key does not exist:
>>> print(stock.get("RIM")
None
>>> stock.get("RIM","Not Found")
'Not Found'
for symbol, values in stock.items():
print ("{} last value is {}".format(symbol,values[0]))
>>> stock.setdefault("GOOG","Not Found")
(1000,1001,999,1001)
>>> stock.setdefault("BBRY",(100,101,102,103))
(100,101,102,103)
>>> stock["BBRY"] #stock.get("BBRY")
(100,101,102,103)
def letter_frequency(sentence):
frequencies = {}
for letter in sentence:
frequency = frequencies.setdefault(letter, 0)
frequencies[letter] = frequency + 1
return frequencies
>>> letter_frequency("this is a short sentence that is used for testing")
{'t': 7,
'h': 3,
'i': 4,
's': 7,
' ': 9,
'a': 2,
'o': 2,
'r': 2,
'e': 5,
'n': 3,
'c': 1,
'u': 1,
'd': 1,
'f': 1,
'g': 1}
Every time we access the dictionary, we need to check that it has a value already, and if not, set it to zero. When something like this needs to be done every time an empty key is requested, we can use a different version of the dictionary, called defaultdict(). The defaultdict accepts a function in its constructor. Whenever a key is accessed that is not already in the dictionary, it calls that function, with no parameters, to create a default value.
from collections import defaultdict
def letter_frequency(sentence):
frequencies = defaultdict(int)
for letter in sentence:
frequencies[letter] += 1
return frequencies
>>> letter_frequency("this is a short sentence that is used for testing")
defaultdict(int,
{'t': 7,
'h': 3,
'i': 4,
's': 7,
' ': 9,
'a': 2,
'o': 2,
'r': 2,
'e': 5,
'n': 3,
'c': 1,
'u': 1,
'd': 1,
'f': 1,
'g': 1})