Oct-13-2018, 03:37 PM
def histogram(s): d = dict() for c in s: if c not in d: d[c] = 1 else: d[c] += 1 return d h = histogram('brontosaurus') print(h)
Output:{'b': 1, 'r': 2, 'o': 2, 'n': 1, 't': 1, 's': 2, 'a': 1, 'u': 2}
Dictionaries have a method called get that takes a key and a default value. If the keyappears in the dictionary, get returns the corresponding value; otherwise, it returns the
default value. For example:
>>> h = histogram('a') >>> h {'a': 1} >>> h.get('a', 0) 1 >>> h.get('b', 0) 0As an exercise, use get to write histogram more concisely. You should be able to eliminate
the if statement.
I don't understand get and that's where I'm stuck