Chapter 3 python3, python3

Source: Internet
Author: User

Chapter 3 python3, python3

In python, the dictionary is another variable container model and can store any type of objects.

Each key-value (key => value) pair of the dictionary uses the colon (:), And each pair is separated by a comma (,The entire dictionary is included in curly brackets ({}), The format is as follows:

d = {key1 : value1, key2 : value2 }
  • The key must be unique, but the value is not required.
  • Values can be of any data type, but keys must be unchangeable, such as strings, numbers, or tuples.

 

Python has built-in dictionaries: dict support. dict stands for dictionary and is also called map in other languages. It is stored with key-value (key-value) and has extremely fast search speed.

For example, suppose you want to find the corresponding Score Based on the name of the student. If you want to use list, you need two lists:

names = ['Michael', 'Bob', 'Tracy']scores = [95, 75, 85]

Given a name, to find the corresponding score, you must first find the corresponding position in names and then get the corresponding score from scores. The longer the list, the longer the time consumption.

If you use dict, you only need a "name"-"score" table to directly search for the score based on the name. No matter how large the table is, the search speed will not slow down. Write a dict in Python as follows:

D = {'Michael ': 95, 'Bob': 75, 'tracy ': 85} print ('Michael's result is:', d ['Michael '])

The above code outputs:

Michael's achievement is: 95

Why is dict search so fast? Because the implementation principle of dict is the same as that of Dictionary lookup. Assume that the dictionary contains 10 thousand Chinese characters and we want to query a word. One way is to flip the dictionary from the first page until we find the desired word, this method is used to search for elements in the list. The larger the list, the slower the query. The second method is to first query the page number corresponding to the word in the dictionary index table (such as the first table), then directly go to the page and find the word. No matter which word you want to search for, this search speed is very fast and will not slow down as the dictionary size increases. Dict is the second implementation method.

 

1. Access the value in the dictionary

Place the corresponding keys in the familiar square brackets, as shown in the following example:

dict = {'Name': 'roy', 'Age': 1, 'Class': 'First'}print("dict['Name']: ", dict['Name'])print("dict['Age']: ", dict['Age'])

The above code outputs:

dict['Name']:  roydict['Age']:  1

 

If the key does not exist, dict reports the following error:

dict = {'Name': 'roy', 'Age': 1, 'Class': 'First'}print("dict['sex']: ", dict['sex'])

The above code outputs:

Traceback (most recent call last):  File "D:/python/teaching/01.py", line 2, in <module>    print("dict['sex']: ", dict['sex'])KeyError: 'sex'

There are two methods to avoid the key nonexistent error: one is to use in to determine whether the key exists:

Dict = {'name': 'roy ', 'age': 1, 'class': 'first'} if 'sex' in dict: print ("dict ['sex']:", dict ['sex']) else: print ('no key = sex element found ')

The above code outputs:

No key = sex element found

The second is through the get () method provided by dict. If the key does not exist, you can return None or your own value:

Dict = {'name': 'roy ', 'age': 1, 'class': 'first'} if dict. get ('sex '): print ("dict ['sex']:", dict ['sex ']) else: print (dict. get ('sex', 'No key = sex element found') # indicates a value.

The above code outputs:

No key = sex element found

Note: When None is returned, the result is not displayed in the Python interaction environment.

 

2. Modify the dictionary

You can add a new key/value pair to a dictionary to modify or delete an existing key/value pair as follows:

Dict = {'name': 'roy ', 'age': 1, 'class ': 'first'} dict ['age'] = 100 # update Agedict ['sex'] = 'male' # Add sexprint ('dict [\ 'Age \ ']:', dict ['age']) print ('dict [\ 'sex \ ']:', dict ['sex '])

The above code outputs:

Dict ['age']: 100 dict ['sex']: Male

 

3. Delete dictionary elements

Only one operation is required to delete a single element and clear the dictionary.

The following example shows how to delete a dictionary using the del command:

Dict = {'name': 'roy ', 'age': 1, 'class ': 'first'} dict ['age'] = 100 # update Agedict ['sex'] = 'male' # Add sexdel dict ['age'] # delete key 'sex' print ('dict: ', dict)

The above code outputs:

Dict: {'name': 'roy ', 'class': 'first', 'sex': 'male '}

 

You can also clear the dictionary with clear:

Dict = {'name': 'roy ', 'age': 1, 'class': 'first'} dict. clear () # clear the dictionary print ('dict: ', dict)

The above code outputs:

dict : {}

 

You can also delete the entire dictionary:

Dict = {'name': 'roy ', 'age': 1, 'class': 'first'} del dict # Delete the dictionary print ('dict:', dict)

The above code outputs:

dict : <class 'dict'>

After del is executed, the dictionary no longer exists.

 

To delete a key, usepop(key)Method. The corresponding value is also deleted from dict:

Dict = {'name': 'roy ', 'age': 1, 'class': 'first'} dict. pop ('name') # delete key 'name' print ('dict: ', dict)

The above code outputs:

dict : {'Age': 1, 'Class': 'First'}

 

Note:There is no relationship between the order in which dict stores data and the order in which keys are placed.

Compared with list, dict has the following features:

Contrary to list:

Therefore, dict is a way to exchange space for time.

Dict can be used in many places that require high-speed search. It is almost everywhere in Python code. Correct Use of dict is very important. The first thing to remember is that the key of dict must beImmutable object.

This is because dict calculates the storage location of value based on the key. If the result of calculating the same key is different each time, dict is completely confused. The algorithm that uses the key to calculate the location is called the Hash algorithm ).

To ensure the correctness of the hash, the object as the key cannot be changed. In Python, strings, integers, and so on are immutable, so you can safely use them as keys. The list is variable and cannot be used as the key.

Related Article

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.