My friends, for reprint please indicate the source: blog.csdn.net/jiangjunsho…

Disclaimer: During the teaching of artificial intelligence technology, many students asked me some python related questions, so in order to let students master more extended knowledge and better understand AI technology, I asked my assistant to share this Python series of tutorials, hoping to help you! Since this Python tutorial is not written by me, it is not as funny and boring as my AI teaching. But its knowledge points or say in place, also worth reading! PS: if you don’t understand this article, please read the previous article first. Step by step, you won’t feel difficult to learn a little every day!

Dictionaries can play many roles in Python. In general, dictionaries can replace searching data structures (because indexing by keys is a search operation) and can represent many types of structured information.

> > > rec = {} > > > rec [' name '] = 'MEL' > > > rec [' age '] = 45 > > > rec [' job '] = 'trainer/writer' > > > > > > print (rec [' name ']) melCopy the code

Especially when nested, Python’s built-in data types make it easy to express structured information. The following example nested a list and a dictionary to express the values of structured attributes:

>>> mel = {'name': 'Mark', ... 'jobs': ['trainer','writer'], ... 'web': 'www.rmi.net/ ~ lutz',... 'home': {'state': 'CO','zip':80513}}Copy the code

When reading the elements of a nested object, simply string the index operations together:

>>> mel['name']

'Mark'

>>> mel['jobs']

['trainer','writer']

>>> mel['jobs'][1]

'writer'

>>> mel['home']['zip']

80513
Copy the code

In addition to being an easy way to store information in a program by keys, some Python extensions provide interfaces that look similar and actually work like dictionaries. Python’s DBM interface, for example, fetches files by keys that look especially like an already open dictionary. Strings are read using key indexes:

Import anydbm file = anydbm. Open ("filename") # Link to file file['key'] = 'data' # Store data by key data = file['key'] # Fetch data by keyCopy the code

If you replace anydbm with shelve in the program code above, you can store entire Python objects this way, too. On the WEB, Python’s CGI scripts support an interface that also looks like a dictionary. A call to cgi.FieldStorage yields a dictionary-like object with one entry for each input field on the client web page:

Import cgi form = cgi.fieldStorage () # Parse form data if 'name' in form: showReply ('Hello,' + form['name'].value)Copy the code