views:

71

answers:

3
sentence = "The quick brown fox jumped over the lazy dog."
characters = {}

for character in sentence:
    characters[character] = characters.get(character,0) + 1 

print(characters)

I don't understand what characters.get(character,0) + 1 is doing, rest all seems pretty straightforward.

Thanks

+3  A: 

Start here http://docs.python.org/tutorial/datastructures.html#dictionaries

Then here http://docs.python.org/library/stdtypes.html#mapping-types-dict

Then here http://docs.python.org/library/stdtypes.html#dict.get

characters.get( key, default )

key is a character

default is 0

If the character is in the dictionary, characters, you get the dictionary object.

If not, you get 0.

S.Lott
+2  A: 

The get method of a dict (like for example characters works just like indexing the dict, except that, if the key is missing, instead of raising a KeyError it returns the default value (if you call .get with just one argument, the key, the default value is None).

So an equivalent Python function (where calling myget(d, k, v) is just like d.get(k, v) might be:

def myget(d, k, v=None):
  try: return d[k]
  except KeyError: return v

The sample code in your Q is clearly trying to count the number of occurrences of each character: if it already has a count for a given character, get returns it (so it's just incremented by one), else get returns 0 (so the incrementing correctly gives 1 at a character's first occurrence in the string).

Alex Martelli
(should be `except KeyError: return v`, I think)
Will McCutchen
@Will, yep, tx -- let me fix the answer.
Alex Martelli
Great explanation, many thanks! :)
Nimbuz
A: 

If d is a dictionary, then d.get(k, v) means, give me the value of k in d, unless k isn't there, in which case give me v. It's being used here to get the current count of the character, which should start at 0 if the character hasn't been encountered before.

Ned Batchelder