“This is the 25th day of my participation in the Gwen Challenge in November. See details: The Last Gwen Challenge in 2021”

Access the dictionary:

Stage 1: Base operation not 6!

If you want to retrieve the value of a key in the dictionary, you can display the corresponding value by accessing the key. The code:

dict = {'line generation': "99"."Data analysis": "99"."Probability theory": "98"}      # create a dictionary


print('Xiao Hong's line score is:'.dict['line generation'])                  # Output line generation results
print('Xiao Hong's line score is:'.dict['Data analysis'])               # Output data analysis results
print('Xiao Hong's line score is:'.dict['Probability theory'])                # Output probability theory grade

Copy the code

Stage 2: Common projects!

(1) get gets the value of the specified key, or none if the key does not exist.

The code:

a = {'dry': 11.'age': 11}
print(a.get('age'))
Copy the code

(2) keys select all keys from the dictionary.

The code:

a = {'dry': 11.'age': 11}
print(a.keys())
Copy the code

(3) values();The code:

a = {'dry': 11.'age': 11}
print(a.values())
Copy the code

(4) items fetch all key-value pairs — usage: dictionary name. Items ()

The code:

a = {'dry': 11.'age': 11}
print(a.items())
Copy the code

(5) setdefault(key) check if there is this key, if there is no increase!

The code:

di2 = {'name':'dry'.'age':18.'sex':'male'}
print(di2.setdefault('name'))
di2.setdefault('name2')
print(di2)
Copy the code

Have you noticed that this dictionary is different from that one, but it does have some things in common? For example: we look up the dictionary, is to look up a word, and then will find out the meaning of the word and a series of information; The dictionary we use now, if we want to look up the value of a key, also by looking up the key of the way to display the corresponding value! Think deeply, everybody!

Extension: What if we want to look up the value of a key pair that does not exist in the dictionary?

The answer is obvious — there will definitely be an error after execution, but we’re just going to see what kind of error this will report! Is stubborn!!

dict = {'line generation': "99"."Data analysis": "99"."Probability theory": "98"}      # create a dictionary

print(Dict [' language score ']:".dict['Language Results'])
Copy the code

🔆 In The End!

Start now, stick to it, a little progress a day, in the near future, you will thank you for your efforts!

This blogger will continue to update the basic column of crawler and crawler combat column, carefully read this article friends, you can like the collection and comment on your feelings after reading. And can follow this blogger, read more crawler in the days ahead!

If there are mistakes or inappropriate words can be pointed out in the comment area, thank you! If reprint this article please contact me for my consent, and mark the source and the name of the blogger, thank you!