Detailed explanation of the use of the built-in method get in Python dictionary

高洛峰
Release: 2017-03-17 17:06:09
Original
2063 people have browsed it

pythonDictionary built-in method get application, if we need to get the dictionary value, we have two methods, one is through dict['key'], the other is dict .get() method.

What I want to share with you today is the get() method of the dictionary.

Here we can use the dictionary to make a small game. Suppose the user enters a string in the terminal: "1" or "2" or "3", and the corresponding content is returned. If other input is made, then Return "error"

Some friends here may use if elif elsejudgment statement to operate. It is indeed possible, but it is more cumbersome. I would like to recommend a dictionary get() method which is very convenient.

info = {'1':'first','2':'second','3':'third'}

number = raw_input('input type you number:' )

print info.get(number,'error')

In this way, one line of code get may be able to complete several lines of code for the python judgment statement.


The above is the detailed content of Detailed explanation of the use of the built-in method get in Python dictionary. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template