Dictionary as a set of counters

Source: Internet
Author: User

Suppose you are given a string and you want to count how many times each letters appears. There are several ways you do it:

  1. You cocould create 26 variables, one for each letter of the alphabet. Then you cocould the string and, for each character, increment the corresponding counter, probably using a chained conditional.
  2. You cocould create a list with 26 elements. then you cocould convert each character to a number (using the built-in function ORD), use the number as an index into the list, and increment the appropriate counter.
  3. You coshould create a dictionary with characters as keys and counters as the corresponding values. the first time you see a character, you wocould add an item to the dictionary. after that you wocould increment the value of an existing item.

Each of these options performs the same computation, but each of them implements that computation in a different way. an implementation is a way of creating a computation; some implementations are better than others. for example, an advantage of the dictionary implementation is that we don't have to know ahead of time which letters appear in the string and we only have to make room for the letters that do appear. here we can use the word list in word study.

 

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.

 

 

From Thinking in Python

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.