What can Python dictionaries be used for?

(*-*)浩
Release: 2019-07-04 13:45:54
Original
7839 people have browsed it

Lists are useful when you need to combine a series of values ​​into a data structure and access each value by number. This chapter describes a data structure whose individual values ​​can be accessed by name. This data structure is called mapping. Dictionaries are the only built-in mapping type in Python where values ​​are not arranged in order but are stored under keys. Keys may be numbers, strings, or tuples.

What can Python dictionaries be used for?

The purpose of the dictionary (recommended learning: Python video tutorial)

The name of the dictionary points out the purpose of this data structure. Ordinary books are suitable for reading from beginning to end, and you can quickly turn to any page if you want, a bit like a list in Python. Dictionaries (everyday dictionaries and Python dictionaries) are designed to allow you to easily find a specific word (key) to know its definition (value).

In many cases, using a dictionary is more appropriate than using a list. The following are some uses of Python dictionaries:

represents the state of the chessboard, where each key is a tuple consisting of coordinates;

Storage file modification time, the key is the file name;

Digital phone/address book.

Suppose you have the following list:

>>> names = ['Alice', 'Beth', 'Cecil', 'Dee-Dee', 'Earl']
Copy after login

What if you want to create a small database in which to store the phone numbers of these people? One way is to create another list. Assuming only four-digit extension numbers are stored, this list would look like:

>>> numbers = ['2341', '9102', '3158', '0142', '5551']
Copy after login

Once you create these lists, you can look up Cecil's phone number like this:

>>> numbers[names.index('Cecil')]
'3158'
Copy after login

This works, but it doesn't Too practical. In fact, you want to be able to do something like this:

>>> phonebook['Cecil']
'3158'
Copy after login

How to achieve this goal? As long as the phonebook is a dictionary.

For more Python related technical articles, please visit the Python Tutorial column to learn!

The above is the detailed content of What can Python dictionaries be used for?. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!