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 be a fairly simple tool once you’re comfortable with them, but there are a few things to be aware of when using them:
• Sequence operation is invalid. Dictionaries are mapping mechanisms, not sequences. Because there is no concept of order between dictionary elements, operations such as concatenation (ordered merging) and sharding (extracting adjacent fragments) cannot be used. If you try to do this, Python will report an error when your program runs.
• Assigning to a new index adds items. Keys are generated when you assign a new key to an existing dictionary object.
• Keys are not always strings. Our examples all use strings as keys, but any immutable object can be a key. For example, you can use integers as keys to make dictionaries look a lot like lists (at least when indexed).
When using a list, it is illegal to assign an offset outside the end of the list:
>>> L = []
>>> L[99] = 'spam'
Traceback (most recent call last):
File "<stdin>",line 1,in ?
IndexError: list assignment index out of range
Copy the code
When using integer keys, dictionaries can mimic the growth of lists with offset assignments:
>>> D = {}
>>> D[99] = 'spam'
>>> D[99]
'spam'
>>> D
{99: 'spam'}
Copy the code
Here, it looks like D is a list of 100 items, but it’s really a dictionary with a single element; The value of key 99 is the string ‘spam’. You can access this structure with offsets like a list. When used like this, dictionaries are much like lists with more flexibility.