Lecture 1: Cognitive dictionary
1. Dictionary: The purpose is to easily search for a specific word (key), to find its definition (value).
- Dictionary surrounded by {}
- Key dictionary is a - value (entry) of the composition (key - value ":" segmentation, key - the value of use, "" splitting)
- The dictionary is the only key, value may not be unique
- Dictionary view the values of a key, the key is to go by the name of view, is through an index list
= {PhoneBook " Ann " : " 15,012,345,678 " , " Alice " : " 15,112,345,678 " } Print (PhoneBook) Print (PhoneBook [ " Alice " ]) Print ( " ====== ==== view the elements in the list === " ) names = [ " Ann " , " Bob " ] Print (names) Print (names [0]) results: { 'Ann': ' 15,012,345,678 ' , ' Alice ' : ' 15,112,345,678 ' } 15,112,345,678 ====== view a list of elements ======= [ ' Ann ' , ' Bob ' ] Ann
Under the following circumstances, the dictionary is more practical than the list:
Represents a forward state of the game, each key is composed by the coordinate values of tuples;
Storage file modification time, with the file name as the key;
Digital phone / address book
2. dict function: it can be converted to a list or dictionary Ganso
phonebook = [("Alice","1234"),("Bob","2345")] d = dict(phonebook) print(d) d["Ann"] = "3456" print(d) d["Alice"] = "1111" print(d) 结果: {'Alice': '1234', 'Bob' : ' 2345 ' } { ' Alice ' : ' 1234 ' , ' Bob ' : ' 2345 ' , ' Ann ' : ' 3456 ' } { ' Alice ' : ' 1111 ' , ' Bob ' : ' 2345 ' , ' Ann ' : ' 3456 '}
phonebook = (["Alice","1234"],["Bob","2345"]) d = dict(phonebook) print(d) d["Ann"] = "3456" print(d) d["Alice"] = "1111" print(d) 结果: {'Alice': '1234', 'Bob' : ' 2345 ' } { ' Alice ' : ' 1234 ' , ' Bob ' : ' 2345 ' , ' Ann ' : ' 3456 ' } { ' Alice ' : ' 1111 ' , ' Bob ' : ' 2345 ' , ' Ann ' : ' 3456 '}
3. The basic dictionary operations
- len (d) d is returned item (key - value pairs) Number
- D [k] to return to the associated value of k
- d [k] = v v to the value associated with the key k
- del d [k] is k delete key entry
- in d d k check whether the entry contains k
= {PhoneBook " Ann " : " 15,012,345,678 " , " Alice " : " 15,112,345,678 " } Print (len (PhoneBook)) # Number of key-value pairs in the output dictionary Print (PhoneBook [ " Alice " ]) PhoneBook [ " Ann " ] = " 010-12345678 " # change the key value Print (PhoneBook [ " Ann " ]) del PhoneBook [ " Alice "] #Delete the corresponding key on the Print (PhoneBook) IF " Ann " in PhoneBook: Print (True) the else : Print (False) IF " Alice " in PhoneBook: Print (True) the else : Print (False) result: 2 15,112,345,678 010 12345678 { ' Ann ' : ' 010-12345678 ' } True False