简体   繁体   中英

How does dict.setdefault() count the number of characters?

I got this code from the book Automate the boring stuff with Python , and I don't understand how the setdefault() method counts the number of unique characters.

Code:

message = 'It was a bright cold day in April, and the clocks were striking thirteen.'
count = {}
for character in message:
    count.setdefault(character, 0)
    count[character] = count[character] + 1
print(count)

According to the book, the setdefault() method searches for the key in the dictionary and if not found updates the dictionary, if found does nothing. But I don't understand the counting behaviour of setdefault and how it is done?

Output:

{' ': 13, ',': 1, '.': 1, 'A': 1, 'I': 1, 'a': 4, 'c': 3, 'b': 1, 'e': 5, 'd': 3, 'g': 2,
 'i': 6, 'h': 3, 'k': 2, 'l': 3, 'o': 2, 'n': 4, 'p': 1, 's': 3, 'r': 5, 't': 6, 'w': 2, 'y': 1}

Please explain this to me.

In your example setdefault() is equivalent to this code...

if character not in count:
    count[character] = 0

This is a nicer way (arguably) to do the same thing:

from collections import defaultdict
message = 'It was a bright cold day in April, and the clocks were striking thirteen.'
count = defaultdict(int)
for character in message:
    count[character] = count[character] + 1
print(count)

It works because the default int is 0.

An even nicer way is as follows:

from collections import Counter
print(Counter(
    'It was a bright cold day in April, '
     'and the clocks were striking thirteen.'))

It would be better to use defaultdict in at least this case.

from collections import defaultdict
count = defaultdict(int)
for character in message:
  count[character] += 1

A defaultdict is constructed with a no argument function which creates an instance of whatever default value should be. If a key is not there then this function provides a value for it and inserts the key, value in the dictionary for you. Since int() returns 0 it is initialized correctly in this case. If you wanted it initialized to some other value, n, then you would do something like

count = defaultdict(lambda : n)

I am using the same textbook and I had the same problem. The answers provided are more sophisticated than the example in question, so they don't actually address the issue: the question above is - how does the code understand that it should count the number of occurrences. It turns out, it doesn't really "count". It just keeps changing the values, until it stops. So here is how I explained it to myself after a long and painful research:

message='It was a bright,\
cold day in April,\
and the clocks were \
striking thirteen.'
count={}   # "count" is set as an empty dictionary, which we want to fill out
for character in message:  # for each character, do the following:
    count.setdefault(character,0)  # if the character is not there,
                                   # take it from the message above
                                   # and set it in the dictionary
                                   # so the new key is a letter (e.g. 'a') and value is 0
                                   # (zero is the only value that we can set by default
                                   # otherwise we would gladly set it to 1 (to start with the 1st occurrence))
                               # but if the character already exists - this line will do nothing! (this is pointed out in the same book, page 110) 
                               # the next time it finds the same character
                               # - which means, its second occurrence -
                               # it won't change the key (letter)
                               # But we still want to change the value, so we write the following line:
    count[character]=count[character]+1  # and this line will change the value e.g. increase it by 1
                                         # because "count[character]",
                                         # is a number,  e.g. count['a'] is 1 after its first occurrence
                                         # This is not an "n=n+1" line that we remember from while loops
                                         # it doesn't mean "increase the number by 1
                                         # and do the same operation from the start"
                                         # it simply changes the value (which is an integer) ,
                                         # which we are currently processing in our dictionary, by 1
                                # to summarize: we want the code to go through the characters
                                # and only react to the first occurence of each of them; so
                                # the setdefault does exactly that; it ignores the values;
                                # second, we want the code to increase the value by 1
                                # each time it encounters the same key; 
                                # So in short:
                                # setdefault deals with the key only if it is new (first occurence)
                                 # and the value can be set to change at each occurence,
                                 # by a simple statement with a "+" operator
                                 # the most important thing to understand here is that
                                 # setdefault ignores the values, so to speak,
                                 # and only takes keys, and even them only if they are newly introduced.
print(count)   # prints the whole obtained dictionary

answer by @egon is very good and it answers the doubts raised here. I just modified the code little bit and hope it will be easy to understand now.

message = 'naga'
count = {}
for character in message:
    count.setdefault(character,0)
    print(count)
    count[character] = count[character] + 1
    print(count)  
print(count)

   and the output will be as follows 

  {'n': 0} # first key and value set in count 
  {'n': 1} # set to this value when count[character] = count[character] + 1 is executed.
  {'n': 1, 'a': 0} # so on 
  {'n': 1, 'a': 1}
  {'g': 0, 'n': 1, 'a': 1}
  {'g': 1, 'n': 1, 'a': 1}
  {'g': 1, 'n': 1, 'a': 1}
  {'g': 1, 'n': 1, 'a': 2}
  {'g': 1, 'n': 1, 'a': 2}
message = 'It was a bright cold day in April, and the clocks were striking thirteen.'
count = {} #This is an empty dictionary. We will add key-value pairs to this dictionary with the help of the following lines of code (The for-loop and its code block).

for character in message: #The loop will run for the number of single characters (Each letter & each space between the words are characters) in the string assigned to 'message'.
                          #That means the loop will run for 73 times.
                          #In each iteration of the loop, 'character' will be set to the current character of the string for the running iteration.
                          #That means the loop will start with 'I' and end with '.'(period). 'I' is the current character of the first iteration and '.' is the current character of the last iteration of the for-loop.

    count.setdefault(character, 0) #If the character assigned to 'character' is not in the 'count' dictionary, then the character will be added to the dictionary as a key with its value being set to 0.
    count[character] = count[character] + 1 #The value of the key (character added as key) of 'count' in the running iteration of the loop is incremented by one.
                                            #As a result of a key's value being incremented, we can track how many times a particular character in the string was iterated.
                                            #^It's because the existing value of the existing key will be incremented by 1 for the number of times the particular character is iterated.
                                            #The accuracy of exactly how many times a value should be incremented is ensured because already existing keys in the dictionary aren't updated with new values by set.default(), as it does so only if the key is missing in the dictionary. 

print(count) #Prints out the dictionary with all the key-value pairs added.
             #The key and its value in each key-value pair represent a specific character from the string assigned to 'message' and the number of times it's found in the string, respectively.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM