A python dictionary is another mutable container model, and can store any type of object, such as strings, numbers, tuples, and other container models.
First, create a dictionary
A dictionary consists of a pair of keys and corresponding values. Dictionaries are also referred to as associative arrays or hash tables. The basic syntax is as follows:
Dict = {'Alice'2341'Beth ' '9102'Cecil'3258' }
You can also create a dictionary like this:
' ABC ' 456 'abc'12398.6(PNs );
Attention:
Each key and value is separated by a colon (:), each pair is comma-delimited, each pair is separated by commas, and the whole is placed in curly braces ({}).
The key must be unique, but the value does not have to be.
The value can take any data type, but it must be immutable, such as a string, number, or tuple.
Second, access the values in the dictionary
Put the corresponding key into the familiar square brackets, the following example:
1#!/usr/bin/python2 3Dict = {'Name':'Zara',' Age':7,'Class':' First'};4 5Print"dict[' Name ']:", dict['Name'];6Print"dict[' age ']:", dict[' Age'];7 #以上实例输出结果:8#dict ['Name']: Zara9#dict [' Age']:7
If the data is accessed using a key that is not in the dictionary, the output error is as follows:
#!/usr/bin/pythondict = { " name ": " Span style= "COLOR: #800000" >zara ", age ": 7 , " class ": " first " ";p rint " ", Dict[" alice "];
#以上实例输出结果:
#dict [' Zara ']:
#Traceback (most recent):
# File "test.py", line 4, <module>
# print "dict[' Alice ']:", dict[' Alice ');
#KeyError: ' Alice ' [/code]
Third, modify the dictionary
The way to add new content to a dictionary is to add a new key/value pair, modify or delete an existing key/value pair as follows:
1#!/usr/bin/python2 3Dict = {'Name':'Zara',' Age':7,'Class':' First'};4 5dict[' Age'] =8; # Update Existing entry6dict['School'] ="DPS School"; # ADDNewentry7 8 9Print"dict[' age ']:", dict[' Age'];TenPrint"dict[' School ']:", dict['School']; One #以上实例输出结果: A#dict [' Age']:8 -#dict ['School']: DPS School
Iv. Deleting a dictionary element
The ability to delete a single element also clears the dictionary, emptying only one operation.
Show Delete a dictionary with the Del command, as in the following example:
1#!/usr/bin/python2 3Dict = {'Name':'Zara',' Age':7,'Class':' First'};4 5Del dict['Name']; # The DELETE key is'Name'the entry6 dict.clear (); # Empty dictionary all entries7 del Dict; # Delete Dictionary8 9Print"dict[' age ']:", dict[' Age'];TenPrint"dict[' School ']:", dict['School']; One #但这会引发一个异常 because the dictionary no longer exists after using del: Adict[' Age']: - #Traceback (most recent): -# File"test.py", line8,inch<module> the# Print"dict[' age ']:", dict[' Age']; -#TypeError:'type' Object isUnsubscriptable
V. Characteristics of dictionary Keys
A dictionary value can take any Python object without restriction, either as a standard object or as a user-defined one, but not a key.
Two important points to keep in mind:
1) The same key is not allowed to appear two times. When created, if the same key is assigned a value of two times, the latter value is remembered, as in the following example:
#!/usr/bin/pythondict= {'Name':'Zara',' Age':7,'Name':'Manni'};p rint"dict[' Name ']:", dict['Name']; #以上实例输出结果: #dict ['Name']: Manni
2) The key must be immutable, so it can be used as a number, string or tuple, so the list is not, the following example:
1#!/usr/bin/python2 3Dict = {['Name']:'Zara',' Age':7};4 5Print"dict[' Name ']:", dict['Name'];6 #以上实例输出结果:7 #Traceback (most recent):8# File"test.py", line3,inch<module>9# dict = {['Name']:'Zara',' Age':7};Ten#TypeError: List objects is unhashable
Six, dictionary built-in functions & methods
The Python dictionary contains the following built-in functions:
1, CMP (Dict1, DICT2): compare two dictionary elements.
2. Len (dict): Calculates the number of dictionary elements, that is, the total number of keys.
3, str (dict): output dictionary printable string representation.
4. Type (variable): Returns the type of the input variable and returns the dictionary type if the variable is a dictionary.
The Python dictionary contains the following built-in methods:
1, Radiansdict.clear (): Delete all elements in the dictionary
2, Radiansdict.copy (): Returns a shallow copy of a dictionary
3. Radiansdict.fromkeys (): Create a new dictionary with the key of the dictionary in sequence seq, Val is the initial value corresponding to all keys in the dictionary
4, Radiansdict.get (Key, Default=none): Returns the value of the specified key if the value does not return the default value in the dictionary
5, Radiansdict.has_key (key): If the key in the dictionary dict returns True, otherwise returns false
6, Radiansdict.items (): Returns a traversed (key, value) tuple array in a list
7, Radiansdict.keys (): Returns a dictionary of all keys in a list
8, Radiansdict.setdefault (Key, Default=none): Similar to get (), but if the key does not already exist in the dictionary, the key will be added and the value will be set to default
9, Radiansdict.update (DICT2): The dictionary dict2 key/value pairs updated to Dict
10. Radiansdict.values (): Returns all values in the dictionary as a list
"Python" Python Dictionary (Dictionary) operation detailed