Python Forum

Full Version: how do i use get for my histogram function?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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 key
appears 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)
0
As 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
get is for java
in python use:
value = your_dict[your_key]
(Oct-13-2018, 05:46 PM)Larz60+ Wrote: [ -> ]get is for java in python use:
value = your_dict[your_key]
Larz, OP means
dic.get(key[,defualt]) method

@OP: what it does is to return default value if key is not present in the dict. If you don't use it, in this case you will get KeyError. So it's a nice way to return default value instead of getting error.
Now, think how you can replace the if statement using dict.get()
def histogram(s):
    d = dict()
    for c in s:
        d[c] = d.get(c, 0) + 1
    return d
h = histogram('brontosaurus')
print(h)
{'b': 1, 'r': 2, 'o': 2, 'n': 1, 't': 1, 's': 2, 'a': 1, 'u': 2}
I don't get what I exactly did there but it worked.
The dict.get() method does value retrieval from the dict (just like dict[key]) with exception checking added. In the event that the key is not in the dict, dict.get() returns the default value you provide. On line 4, you used:

d[c] = d.get(c, 0) + 1
In your code, dict.get() searches dict "d" for key "c". If "c" is not found, it returns the default of 0. If "c" is found, it returns the value of "c" in the dict. In either case, it then adds 1 to the value returned by dict.get() and assigns the value of "c" in the dict to the new value.

In effect, that line replaces this in the original:

if c not in d:
    d[c] = 1
else:
    d[c] += 1