Last week summed up some of Python's basic data types and usage. This concludes the contents of chapter 4-9, after the completion, hurriedly apply it.
5. Fourth-dictionary: When the index is not good
The dictionary is the only built-in mapping type in Python. The values in the dictionary are not in a special order, but are stored in a specific key. A key can be a number, a string, or even a tuple. In fact, students who have used JSON will find Python's dictionary very kind.
5.1. Create a dictionary
1 >>> phonebook = {'Alice'2341' Beth ' ' 9102 ' ' Cecil ' ' 3258 '}
1>>> items = [('name','Gumby'),(' Age', 42)]2>>> Phonebook =dict (items)3>>>Phonebook4{' Age': 42,'name':'Gumby'}
1 >>> items = dict (name='Gumby', age=42)2 >> > Items3 {'age''name' Gumby'}
1>>> {}.fromkeys (['name',' Age'])2{' Age': None,'name': None}3>>> Dict.fromkeys (['name',' Age'])4{' Age': None,'name': None}5>>> Dict.fromkeys (['name',' Age'],'Unknown')6{' Age':'Unknown','name':'Unknown'}
5.2. Using a dictionary
1 >>> items2 {'age''name' 'Gumby'}3"% (name) s ' s ' age ' s. " % items4"Gumby ' s is a. "
1>>> template =" "2 ... 3 ... <body>4 ... 5 ... <p>% (text) s</p>6 ... </body>" "7>>> data = {'title':'Panderen Home','text':'Welcome to my home page'}8>>>PrintTemplate%Data9Ten One<body> A -<p>welcome to my home page</p> -</body>
5.3. Dictionary methods
- The clear () method clears the value, and ={} is a reference to the variable (similar to the C language pointer);
- Copy (), the Deepcopy () method, copying () copies the reference, and as long as you change one, the values in the other variables change. The Deepcopy () method copies the values, each of the tubes;
- Fromkeys method, 5.1 mentioned;
- Get () method, Items.get (' name ', ' N/A '), parameter one is the key, parameter two is the default value;
- Has_key () method, whether there is a key, return ture or False;
- Items () Returns a list, Iteritems () returns an iterator;
- Keys () returns a list of Iterkeys () iterators;
- Pop () method, Items.pop (' X ');
- Popitem () method, which is similar to List.pop (), but the latter pops up the last element of the list. Popitem () popup random item;
- SetDefault () method, Items.setdefault (' name ', ' N/A '). Do not set the default value, the system will use none;
- Update () method that updates the contents of another dictionary with one dictionary entry;
- VALUES () returns a value in the form of a list, itervalues () returns an iterator.
Summary of Basic Python tutorials (II.)