Summary of common methods of operation for Python dictionaries

Source: Internet
Author: User
Tags dota
A python dictionary is another mutable container model (unordered), and can store any type of object, such as strings, numbers, tuples, and other container models. This article mainly introduces the Python dictionary (Dict) The detailed operation method, contains the creation, the access, the deletion, the other operation and so on, needs the friend to be possible the reference.

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:

1. Create a dictionary

>>> dict = {' Ob1 ': ' Computer ', ' ob2 ': ' Mouse ', ' ob3 ': ' Printer '} Tip: The dictionary contains the list: dict={' yangrong ': [' ['] ', ' IT '], ' Xiaohei ": [' ['] ', ' DotA ']} Dictionary contains dictionary: dict={' yangrong ': {" Age ":" "", "Job": "IT"}, "Xiaohei": {"' Age ': ' '", ' job ': ' DotA '}} Note: 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.

2. Accessing values in the dictionary

>>> dict = {' Ob1 ': ' Computer ', ' ob2 ': ' Mouse ', ' ob3 ': ' Printer '}>>> print (dict[' ob1 ') Computer if the data is accessed using a key not in the dictionary, the output error is as follows:>>> print (dict[' ob4 ') Traceback (most recent call last): File "
 
  
   
  ", line 1, in 
  
   
    
     print (dict[' ob4 ')) Access all values >>> Dict1 = {' Ob1 ': ' Computer ', ' ob2 ': ' Mouse ', ' ob3 ': ' Printer '}>>> for key in Dict1:  print (Key,dict1[key])  ob3 printerob2 mouseob1 computer
  
   
 
  

3. Modify the Dictionary

>>> dict = {' Ob1 ': ' Computer ', ' ob2 ': ' Mouse ', ' ob3 ': ' Printer '}>>> dict[' ob1 ']= ' book ' >>> Print (dict) {' ob3 ': ' Printer ', ' ob2 ': ' Mouse ', ' ob1 ': ' Book '}

4. Delete a dictionary

can delete single element >>> dict = {' Ob1 ': ' Computer ', ' ob2 ': ' Mouse ', ' ob3 ': ' Printer '}>>> del dict[' Ob1 ']>>> Print (dict) {' ob3 ': ' Printer ', ' ob2 ': ' Mouse '} Delete all elements in the dictionary >>> dict1={' ob1 ': ' Computer ', ' ob2 ': ' Mouse ', ' ob1 ': ' Printer '}>>> dict1.clear () >>> print (Dict1) {} Deletes the entire dictionary, and the access to the dictionary after deletion throws an exception. >>> Dict1 = {' Ob1 ': ' Computer ', ' ob2 ': ' Mouse ', ' ob3 ': ' Printer '}>>> del dict1>>> print (DICT1) Traceback (most recent): File "
 
  
   
  ", line 1, in 
  
   
    
     print (dict1) nameerror:name ' Dict1 ' is n OT defined
  
   
 
  

5. Updating dictionaries

The update () method can be used to add the contents of a dictionary to another dictionary:>>> dict1 = {' Ob1 ': ' Computer ', ' ob2 ': ' Mouse '}>>> dict2={' ob3 ': ' Printer '}>>> dict1.update (dict2) >>> print (dict1) {' ob3 ': ' Printer ', ' ob2 ': ' Mouse ', ' ob1 ': ' Computer '}

6. Mapping type-related functions

>>> dict (x=1, y=2) {' Y ': 2, ' X ': 1} >>> dict8 = Dict (x=1, y=2) >>> dict8 {' Y ': 2, ' X ': 1} >& gt;> dict9 = dict (**dict8) >>> dict9 {' Y ': 2, ' X ': 1}  Dict9 = Dict8.copy ()

7. 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 remember: 1) do not allow the same key to appear two times. When created, if the same key is assigned two times, the latter value is remembered  >>> dict1={' ob1 ': ' Computer ', ' ob2 ': ' Mouse ', ' ob1 ': ' Printer '}>>> Print (Dict1) {' ob2 ': ' Mouse ', ' ob1 ': ' Printer '}  2) The key must be immutable, so it can be used as a number, string or tuple, not with a list >>> Dict1 = {[' Ob1 ']: ' Computer ', ' ob2 ': ' Mouse ', ' ob3 ': ' Printer '}traceback (most recent call last): File "
 
  
   
  ", line 1, in 
  
   
    dict1 = {[' Ob1 ']: ' computer ', ' ob2 ': ' Mouse ', ' ob3 ': ' Printer '}typeerror:unhashable type: ' list '
  
   
 
  

8. Dictionary built-in functions & methods

The Python dictionary contains the following built-in functions: 1, CMP (Dict1, DICT2): compare two dictionary elements. (Not available after Python3) 2, Len (dict): Calculates the number of dictionary elements, that is, the total number of keys. 3. STR (DICT): Output dictionary printable string. 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 () : Creates a new dictionary with the key of the dictionary in sequence seq, Val is the initial value of all keys for the dictionary 4, Radiansdict.get (Key, Default=none): Returns the value of the specified key, if the value does not return the default value 5 in the dictionary, Radiansdict.has_key (Key): If the key returns true in the dictionary dict, returns FALSE6, Radiansdict.items (): Returns the iterated (key, value) tuple array in the list 7, Radiansdict.keys (): Returns a dictionary with a list of all keys 8, Radiansdict.setdefault (Key, Default=none): Similar to get (), but if the key does not already exist in the dictionary, the key is added and the value is set to Default9, Radiansdict.update (DICT2): Update dictionary dict2 key/value pairs to dict 10, radiansdict.values (): Returns all values in the dictionary as a list

Above this Python dictionary common operation method Summary is small part to share to everyone's content, hope to give you a reference, also hope that we support the script house a lot.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.