The use of the built-in method get in python dictionary

高洛峰
Release: 2016-10-19 11:54:28
Original
1379 people have browsed it

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

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

Here we can use the dictionary to make a small game. Assume that the user enters a string in the terminal: "1" or "2" or "3", and the corresponding content is returned. If other characters are entered, "error" is returned.

Some friends here may use if elif else judgment statements 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 can complete several lines of code for the python judgment statement.


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