This article is participating in Python Theme Month. See the link to the event for more details

preface

After studying tuples in five Minutes a Day (9), many students asked me, how do my tuples modify the elements in them? In fact, the students who asked this question did not understand the characteristics of tuples, I suggest you to check the last lesson again carefully! So if you have to change it, I can give you the idea of forcing the tuple to be a list using the list() function, and then you can change it. Ok, so let’s get started!

What is a dictionary

A dictionary is also a common data structure provided by Python, which is used to hold data with mapping relationships. (Ps: For those of you who have studied other programming languages, dictionaries are very similar to JSON data.)

Do you think you don’t quite understand what the above sentence means? If you don’t understand, I’ll give you an example of what a dictionary is

For example, there is the score table data —– : Language: 80, math: 60, English: 100. This set of data looks like two lists, but there is a certain correlation between the elements of the two lists. If you use only two lists to hold this set of data, you cannot record the association between the two sets of data.

To hold mapped data, Python provides a dictionary. A dictionary holds two sets of data. One set of data is key, called key. Another set of data can be accessed through a key, called a value. Visually, the relationship between key and value in a dictionary is as follows:It is important to note that since keys in a dictionary are critical data and the program needs to access values through keys, keys in a dictionary are not allowed to be repeated

Create a dictionary

Use curly braces {} to create a dictionary. The curly braces should contain multiple key-value pairs. Separate key and value with colons. Use commas (,) to separate multiple key-value pairs. Example:

scores = {'Chinese': 89.'mathematics': 60.'English':100}
print(scores) {'Chinese': 89.'mathematics': 60.'English': 100}
Copy the code

It is also possible to create a dictionary using the dict() function, for example:

scores = [('Chinese'.89), ('mathematics'.60), ('English'.100)]
scores_dict = dict(scores)
print(scores_dict) {'Chinese': 89.'mathematics': 60.'English': 100}
Copy the code

(Note: you cannot use quotation marks when using this method, otherwise an error will be reported.)

scores = dictChinese = (80Mathematics =50English =100)
print(scores) {'Chinese': 80.'mathematics': 50.'English': 100}
Copy the code

Access to a dictionary

Ex. :

scores = dictChinese = (80Mathematics =50English =100)
print(scores['Chinese']) output:80
Copy the code

To modify a dictionary

Ex. :

scores = dictChinese = (80Mathematics =50English =100)
scores['Chinese'] = 100
print(scores) {'Chinese': 100.'mathematics': 50.'English': 100}
Copy the code

Changing the value of a nonexistent key is equivalent to adding a new element. For example:

scores = dictChinese = (80Mathematics =50English =100)
scores['physical'] = 100
print(scores) {'Chinese': 80.'mathematics': 50.'English': 100.'physical': 100}
Copy the code

Delete dictionary (del)

Ex. :

scores = dictChinese = (80Mathematics =50English =100)
scores['physical'] = 100
del scores['English']
print(scores) {'Chinese': 80.'mathematics': 50.'physical': 100}
Copy the code

Determine if there is an element in the dictionary (in/not in)

Ex. :

scores = dictChinese = (80Mathematics =50English =100)
scores['physical'] = 100
print('English' inScores) Output result:True
Copy the code
scores = dictChinese = (80Mathematics =50English =100)
scores['physical'] = 100
print('chemistry' not inScores) Output result:True
Copy the code

Dictionary common methods

Get () : obtains a value based on the key

scores = dictChinese = (80Mathematics =50English =100)
print(scores.get('English') Output result:100
Copy the code

Update () : An example of an existing field can be updated using a key-value pair contained in a dictionary:

scores = dictChinese = (80Mathematics =50English =100)
scores.update({'Chinese':90.'English':80})
print(scores) {'Chinese': 90.'mathematics': 50.'English': 80}
Copy the code

Items () : retrieves all key-value pairs in a dictionary.

scores ={'Chinese': 80.'mathematics':50.'English':100}
ims = scores.items()
print(list(ims)[1]) Output: ('mathematics'.50)
Copy the code

Keys () : get all keys in the dictionary

scores ={'Chinese': 80.'mathematics':50.'English':100}
ims = scores.keys()
printDict_keys (['Chinese'.'mathematics'.'English'])
Copy the code

Values () : obtain all values in the dictionary. Example:

scores ={'Chinese': 80.'mathematics':50.'English':100}
ims = scores.values()
printDict_values ([80.50.100])
Copy the code

Pop () : to get the value corresponding to the specified key and delete the key-value pair:

scores ={'Chinese': 80.'mathematics':50.'English':100}
scores.pop('Chinese')
print(scores) {'mathematics': 50.'English': 100}
Copy the code

Fromkeys () : creates a dictionary with a given number of keys whose value defaults to None; You can also pass in an extra parameter as the default value. This method is usually not called using a dictionary object (which makes no sense), and is usually called directly using a dict class. Ex. :

a_dict = dict.fromkeys(['a'.'b'])
print(a_dict) {'a': None.'b': None}
Copy the code
a_dict = dict.fromkeys((13.17),'good')
print(a_dict) {13: 'good'.17: 'good'}
Copy the code

Format strings using dictionaries

Specify a variable in the string template by key, and then set an example value for the key in the string template using a dictionary:

temp = 'the title is: % (name) s, the price is: % 010.2 f (price), publishing house is: % (publish) s'
book = {'name':'crazy python'.'price':88.9.'publish':'Electronic Club'}
print(temp % book)0000088.90The publishing house is: Electronic societyCopy the code

After-class supervision

Recently a part of the students in the background of private chat I said, I am ready to learn every day, but a go to the computer desk is not up to work, how to do? For students in this situation, I decide to spend some time every day to supervise and tutor your study. If you need any help, please scan the pictures below and click “Contact author” to sign up.

conclusion

The content of the course is only so much, I hope that every student can conscientiously learn every lesson, remember that the road of learning programming is really a little bitter, but every day can stick to it, there will be a lot of harvest, the next class will talk about the numeric types of variables and the use of operators, please look forward to.