Home > Article > Backend Development > What can Python dictionaries be used for?
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.
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']
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']
Once you create these lists, you can look up Cecil's phone number like this:
>>> numbers[names.index('Cecil')] '3158'
This works, but it doesn't Too practical. In fact, you want to be able to do something like this:
>>> phonebook['Cecil'] '3158'
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!