[Tutor] dict.get() vs. dict.get

memilanuk memilanuk at gmail.com
Fri Aug 1 04:56:23 CEST 2014


What is the difference between dict.get() and dict.get as shown in the 
code below:

counts = dict()

for line in input_file:
     words = line.split()
     if len(words) == 0:
         continue
     else:
         if words[0] != 'From:':
             continue
         else:
             counts[words[1]] = counts.get(words[1], 0) + 1

max_key = max(counts, key=counts.get)
max_value = counts[max_key]

print max_key, max_value

I know the former (counts.get()) is supposed to return a value for a key 
if it exists, or else return the default value (in this case '0').  That 
part of the code is checking to see if the value contained in words[1] 
exists as a key in the dictionary counts or not; either way increment 
the associated value by +1.

The latter (counts.get) reflects some code I found online [1]:

print max(d.keys(), key=lambda x: d[x])

or even shorter (from comment):

print max(d, key=d.get)

that is to replace manually looping through the dict to find the max 
value like this:

max_value = None
max_key = None

for key, value in counts.items():
     if max_value is None or max_value < value:
         max_value = value
         max_key = key

print max_key, max_value


So... the similarity between dict.get() and dict.get as used here is 
kinda confusing me.  When I do a search for 'dict.get' in the python 
docs or on google all I normally find is stuff referring to 'dict.get()'.

Any pointers would be much appreciated.


[1] 
http://stackoverflow.com/questions/12402015/print-the-key-of-the-max-value-in-a-dictionary-the-pythonic-way
-- 
Shiny!  Let's be bad guys.

Reach me @ memilanuk (at) gmail dot com



More information about the Tutor mailing list