This article corresponds to exercise 39 dictionaries and cute dictionaries.
# Encoding: UTF-8 # differences between the list and dictionary # list thing = ['name', 1, 'age', 'ad ', 'sex'] print thing [1] # print thing ['name'] # An error is returned. The list can only be accessed through an integer: TypeError: list indices must be integers, not strstuff = {'name': 'Tom ', 'age': '28', '1 ': 'test'} print stuff ['name'] # print stuff [1] # An error is returned. Keyword error KeyError: 1 # The dictionary can only be accessed through its own index, the list is accessed through the Index given by the system # print stuff ['Tom '] # keyword error KeyError: 'Tom' # Through the above, we can know, (1) the list is different from the dictionary definition. [] and {} are different. (2) The access element method is different. The list is an integer 0 1 2 provided by the system .... access, while the dictionary index is self-defined 'A': 'B' a is the index, and B is the corresponding element # Add the element thing to the list. append ('new1') # You can use the insert method to insert thing. insert (1, 'new2') # The following method is incorrect IndexError: list assignment index out of range # thing [4] = 'new2' for I in thing: print I # The index position of an element in the list query print thing. index ('name') # delete an element from the list. The parameter is this element and it is not an element index thing. remove ('age') # You can also use pop to delete the data. The deleted Value print thing will be returned during deletion. pop () # print thing is deleted by default without parameters. pop (0) # There is also a reverse (reverse sorting) sortprint thing, U' stuff. the result 'thing. sort () print thing, 'stuff. sort () Result '# The dictionary adds the element stuff ['job'] = 'it' # setdefault. If this index exists, the element value of the index is returned. If IT does not exist, stuff is inserted. setdefault ('new4', 'default') # update an element, stuff ['job'] = 'it1' # for I in stuff: # print iprint stuff ['job'] # The pop Method for deleting an element in the dictionary. Its usage is the same as that in the list: print stuffprint stuff. pop ("job"), 'stuff. pop () Result 'print stuff # obtain a value of print stuff. get ("new4") # returns the entire dictionary print stuff. items (), 'stuff. items () Result '# values prints the value of the list out print stuff. values (), 'stuff. result of values'