# dict# python built-in dictionary: dict support, Dict full name dictionary, also known as map in other languages, using key-value (Key-value) storage, with extremely fast search speed. d = {' Michael ': 95, ' Bob ': 75, ' Tracy ': 85}print (' dict get Michael: ' d[' Michael ']) # add a elementd[' Adam '] = 67print (' dict d ', d ) # change a elementd[' Adam '] = 90print (' dict get ' Adam ' after Change ', d[' Adam ') # if key not exist,there is an error of Dict: (key error: ' Thomas ') # print (' Dict get an element,is not exist ', d [' Thomas ']) # avoid the key does not exist errors, there are two ways to # 1. Determine if key exists if ' Thomas ' in d: print (' the key "Thomas" exist ') else: print (' the key ' Thomas ' not exist ') # 2. With the Get method provided by Dict, if key does not exist, you can return none, or your own specified Valueprint (' get not exist element "Thomas" ', &Nbsp;d.get (' Thomas ') print (' get not exist element ' Thomas ', d.get (' Thomas ', -1) ) # delete an elementd.pop (' Bob ') print (' Dict d after delete the element of key "Bob" ', d) # dict internal storage order and key into the order is not related to the # and list comparison, Dict has the following features: # 1. The search and insertion speed is very fast and does not slow with the increase of key; # 2. Requires a lot of memory, memory waste # and list opposite: # 1. The time to find and insert increases as the element increases; # 2. Takes up little space, A waste of memory is scarce. # So, Dict is a way of exchanging space for time. # dict can be used in many places where high-speed lookups are needed, everywhere in Python code, the proper use of dict is important, and the first thing to keep in mind is that the Dict key must be an immutable object. # This is because Dict calculates the storage location of value based on key, and if each calculation of the same key results in a different result, the dict interior is completely chaotic. The algorithm for calculating the position by key is called a hashing algorithm. # to ensure the correctness of the hash, as a key object can not be changed. In Python, strings, integers, and so on are immutable, so you can safely use them as keys. The list is mutable and cannot be used as a key# typeerror: unhashable type: ' list ' # key = [1, 2, 3]# d[key] = ' A list '
The dict in Python