Python's list and dictionary

Source: Internet
Author: User

1.4 lists and dictionaries

Lists and dictionaries, both types, are collections of various types, and in the case of lists, nesting is formed if the list contains lists. these two types are almost the main working components of all Python scripts . This structure information is mutable and modifiable. Unlike constants, once defined, they can no longer be modified.

  • [X]List lists have the following major attributes, or features:
      1. An ordered set of arbitrary objects
      2. To read by offset
      3. Variable length, heterogeneous and arbitrary nesting
      4. The list is mutable and can be modified, added, merged, deleted, and so on, in contrast to strings and constants.
      5. Object reference Array
      6. List elements are separated by commas

    In the standard Python parser, the list is the C array, not the link structure.

    • [X]Operation of the list

      On the list, we can use Help (list) or Dir (list), or replace the keyword list with a real listing to see the aid document. In addition, there are some other fixed available operations. Here are some common simple list manipulation methods:

      Table 7: List Operations
      Method Interpretation Example
      L=[] Definition List L=[' A ', 2,[' B ', ' c,d ']
      L=list (...) Definition List
      L=[c * 4 for C in ' Hal '] Definition List
      L.append () Add new member at the end of list, list, dictionary function new member L.append ([' A ', 2, ' B ')
      L.clear () Clear List L.clear ()
      L.copy (value) Copy List L.copy ()
      L.count (value) Count the number of times a member appears in a list L.count (' B '), L.count (L1, 2)
      L.extend (value) Add new content (in the case of a list, a dictionary, the L.extend ([3,{4,5}])
      Dictionaries, members of the list are added to the original list, and their
      The child list functions as a whole add). If the type (value
      =list is merged, if type (value) is =set, then
      The values in the dictionary are added in reverse order, and if it is a string, go
      Merged into a dictionary.
      List cannot be added such as L.extend ({4,[' a '})
      L.index (Value,[start,[stop]) Returns the index number corresponding to the value in the list. In.
      Start–> stop between if there is no need to find
      The value, then the error L.index ({4,5})
      L.insert (Index,object) Add a new list member before the specified index location L.insert (2,{' A ', ' B '})
      L.pop ([index]) Deletes the content according to the index location.
      The value of index must be a single integer, not a list, word
      In the form of a code, that is, you can delete only one list at a time
      Members. An error if the specified index does not exist. If you do not refer to L.pop (3)
      Index value, the last member is deleted by default.
      L.remove (object) Exclude members from the list. Object must be a full member L.remove ({' A ', ' B '})
      L.reverse () Order list members in reverse order L.reverse ()
      L.sort (Key=none,reverse=false)) The method is sorted by default in ascending order. When Reverse=ture, enter
      Row reversed order. But python3.0 a little bit different before and after:
      before 3.0, the ordering between different elements is allowed .
      After 3.0, different types of list elements are not allowed to be sorted L.sort ()
      l*2 repeating list contents  
      list (' Hal ') +list (' Berd ') list merge, actually generated a new list  
      l[i:j]=[]  
         
      len (l) Returns the number of list elements  
      3 in L Judging if the list L is a 3 element, note data type  
      del l[[index]]  
      Thinking
      Add new elements to the list by using the index.
      Answer: L[len[l]:]=[x]; L[:0]=[X] Use the index to adjust the list, you can implement functions such as append,remove,pop,insert. Note that you add the data type of the new element. such as lists and strings
  • [X]A dictionary dictionary can be said to be the most flexible built-in data structure outside the list. The dictionary has the following properties:
    1. The key must be an immutable type by accessing the value rather than by the offset.
    2. Dictionary elements are unordered collections
    3. Variable length, heterogeneous, arbitrary nesting
    4. belongs to a mutable mapping type
    5. Hash list. Data retrieval by hash operation. Stores a reference to the object as a list instead of a copy.
      • Dictionary Operations
        Table 8: Dictionary operations
        Method Interpretation Example
        d={} Define an empty dictionary d={}
        D={' A ': ' B ', ' Name ': ' Halberd '} Defining dictionaries d={' name ': ' Halberd '}
        D=dict (Mappint) Define dictionaries, which are more complex and difficult to understand. Since Dict can only accept D=dict ((' Key1 ', ' value1 '), (' Key2 ', ' value2 '),...))
        A parameter, so inside the Dict () method must contain a representation of the
        The whole symbol, available for "()," "[]," but "{}," cannot be used, Dict (())
        or dict ([]), which is the Key/value value information in the most internal, so
        To form a three-storey structure:
        The first layer is: Dict ()
        The second layer is: Dict (()) or dict ([])
        The third layer is: dict ([' Key1 ', ' value1 '], (' Key2 ', ' value2 '),...))
        D=dict (Zip (keys,values)) Defines a dictionary. where keys, and the types of values, can be strings, respectively,
        List, or a series of values returned by a function such as range (), etc. D=dict (Zip (' ABCD ', Range (1,5)))
        D.clear () Empty the dictionary without passing in any parameters. D.clear ()
        D.copy () Copy the original dictionary out of a new dictionary E=d.copy ()
        D.fromkeys (Iterable,value) Defines the keys in a dictionary and assigns the same values. Value defaults to None Dict.fromkeys ([' A ', ' B '], ' 123 ')
        Iterable can be a list, or it can be a dictionary. If it is a list, the list Dict.fromkeys ({' name ': ' Halberd ', ' age ': 20},100)
        Each member is converted to a key, and if it is a dictionary, value is assigned to the dictionary
        The key in
        D.get (Key[,values]) Remove the value from the dictionary key. You can also use value to give a new value. But
        Has no effect on the original dictionary. The key in the dictionary is removed when the value part is not written
        The corresponding value, at this time equivalent to Dict[key]. Write value, and the result is D.get (' name ' [, ' Guess '])
        Value
        D.items () Returns an array of traversed (key, value) tuples as a list D.items ()
        D.keys () Returns a dictionary of all keys in a list D.keys ()
        D.values Returns a dictionary of all values in a list D.values ()
        D.pop (Key[,value]) Delete key in dictionary and corresponding value, same as Del D[key] D.pop (' name ' [, ' halberd '])
        D.popitem () This method does not require any parameters, and the last Key:value is deleted by default. Returned by d={' name ': ' Halberd ', ' age ': 2, ' gender ': ' Male '}
        is the deleted key and the corresponding value, returned as a tuple, but if it is empty D.popitem ()
        Dictionary, the error message is returned
        D.setdefault (Key[,value])) Returns the value corresponding to key, but if key does not exist in the original dictionary, append D.setdefault (' Gender ', ' male ')
        If key does not exist and no corresponding value is provided, the default is ' None '
        D.update () 1. Merge dictionaries. For example, Dict1 and Dict2 dict1.update (DICT2) will d2={' gender ': ' Male '}
        The contents of the Dict2 are merged into Dict1, and if Dict2 is included in the Dict1, there is no change D.update (D2)
        2. DICT1 uses update to add other types of data to the dictionary Key:value D.update (work= ' it-migrant-worker ', married= ' NO ')
        Merge into the Dict1- D.update ([' Work ', ' it-migrant-worker '],[' married ', ' NO '))
        D.update ([' Work ', ' It-migrant-worker '), (' Married ', ' NO ')])
        D.update (Zip (' work ', ' married '), (' It-migrant-worker ', ' NO '))
        D.update (Zip ([' Work ', ' married '],[' it-migrant-worker ', ' NO '))
        Len (dict) Calculate the number of dictionary Key=value Len (d)
        Del Dict[key] Delete a key and corresponding value in the dictionary with Dict.pop (key) Del d[' name ']
        Del Dict Delete Dictionary Del D

Python's list and dictionary

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.