A detailed introduction to dictionaries and collections in Python

Source: Internet
Author: User
Tags shallow copy
Dictionaries and collections in Python

Mapping Type:    represents a collection of arbitrary objects, and can be indexed and serialized differently by another collection of almost any key value, which    is unordered and indexed by key        any immutable object can be used as a dictionary key, such as a string, a number, a tuple, and so on        . Lists, dictionaries, and tuples that contain mutable objects cannot be used as keys        that do not exist as key references throw keyerror exceptions

1) Dictionary

    dict {} empty dictionary {key1:value1,key2:value2,...}        Dictionaries are also referred to as associative arrays or hash lists in other programming languages, access to elements through keys, unordered collections, mutable type containers, variable-length, heterogeneous, nested supported operations:                     Len (d) Returns the number of items in D d[k] Returns the value of the key K in d d[k] = X                    Set the value of D[k] to x >>> d1 = {' x ': 1, ' Y ': 2, ' Z ': 3}                    >>> d1[' x '] 1 >>> d1[' z '] indexed by key 3 del d[k] remove d[k from D] >>> del d1[' x '] ;>> d1 {' Y ': 2, ' Z ': 3} k in D if K is a value in D, returns true for the supported party Method: D.clear () Clears all elements d.copy () copies a copy >>> d1            = {' X ': 1, ' Y ': 2, ' Z ': 3} >>> ID (d1)        45320640 >>> d2 = d1.copy () deep copy >>> ID (D2)                    45997776 >>> d3 = d1 Shallow Copy                >>> ID (D3) 45320640 D1, D3 points to the same object, D2 points to another object D.get (K[,d])                Gets the value of the corresponding key, returns D if it does not exist (default is empty) >>> d1.get (' y ') 2 D.has_key (k) Whether a key value exists, returns TRUE or false.        (used in Pyhton2 only)  D.items () converted to a (key,value) tuple consisting of the list >>> d1.items () [(' Y ', 2),                    (' x ', 1), (' Z ', 3)] >>> t1,t2,t3 = D1.items () >>> t1                    (' Y ', 2) >>> T2 (' x ', 1) >>> T3                   (' Z ', 3) >>> m1,m2 = {' x ': 1, ' Y ': 2} >>> print M1 ' y ' >>> print m2 ' x '        The key is saved, not the value!!!                    D.values () value list >>> d1.values () [2, 1, 3] D.keys ()                Key list >>> D1.keys () [' Y ', ' x ', ' Z '] D.pop (K[,d])  Eject the specified key value, if not specified, will trigger an exception >>> D1.pop () typeerror:pop expected at least                    1 arguments, got 0 >>> D1.pop (' x ') 1 >>> d1 {' Y ': 2, ' Z ': 3} d.popitem () random pop-up >>> D1.popitem (                    ) (' Y ', 2) >>> d1.popitem (' Z ', 3)   >>> D1.popitem () Keyerror: ' Popitem (): Dictionary is empty '            Merge dictionaries for empty-time exceptions >>> D1 {} d.update (m)                    >>> D1 = {' x ': 1, ' Y ': 2, ' Z ': 3} >>> d2={' C ': ' Hello ', ' Y ': 66} >>> d1.update (D2) >>> d1 {' Y ': £ º ' x ': 1, ' C ': ' Hello ', ' Z ': 3} If the key is present, it will overwrite, not exist add D.iteritems () to return an iterator object >>> d1                   = {' X ': 1, ' Y ': 2, ' Z ': 3} >>> I1 = D1.iteritems () >>> I1.next () Use the next method to traverse each element (' Y ', 2) >>> I1.next () (' X                    ': 1) >>> I1.next () (' Z ': 3) >>> I1.next ()  Stopiteration does not restart after the end of the traversal D.iterkeys ()-a iterator over the keys of D ≫>> i2 = D1.iterkey () >>> i2.next () ' Y ' d.itervalues ()- > A iterator over the values of D >>> i3 = D1.iterkey () >>&G T I3.next () 2 d.viewvalues () returns a dictionary of similar collections (value composition) >  >> d1.viewvalues () dict_values ([2, 1, 3]) D.viewitems (), a Set-like object Providing a view on D ' s items (key-value pairs) >>> d1.viewitems () dict_items ([' Y ', 2)                    , (' x ', 1), (' Z ', 3)]) D.viewkeys () a Set-like object providing a view on D ' s keys >>> D1.viewkeys () Dict_keys ([' Y ', ' x ', ' Z ']) >& gt;> D2 = dict (x=1,y=2,z=3) define a dictionary another way >>> d2 {' Y ': 2, ' x ': 1, ' Z ': 3} supplement: Zip  Returns a list of tuples consisting of >>> zip (' xyz ', ' 123 ') [(' X ', ' 1 '), (' Y ', ' 2 '), (' Z ', ' 3 ')] one by one corresponding to the build list >>> zip (' xyzm ', ' 123 ') [(' X ', ' 1 '), (' Y ', ' 2 '), (' Z ', ' 3 ')] superfluous items are discarded >                            >> zip (' xyz ', ' 123 ', ' Qer ') [(' X ', ' 1 ', ' Q '), (' Y ', ' 2 ', ' E '), (' Z ', ' 3 ', ' R ')] >>> dict (' xyz ', ' 123 ') constructs the dictionary {' Y ': ' 2 ', ' X ': ' 1 ', ' Z ': ' 3 '}

2) Collection

  Unordered arrangement, hash,  support set relationship Test        member relationship test:  in Don't in iteration not supported: index, Element get, slice  collection type:  set ()    Frozenset ()                mutable immutable  No specific syntax format can only be created by factory function         Example:            >>> s1=set (TypeError)                                                   : Set expected at most 1 arguments, got 3              error mode            >>> S1 = set ([])                                           correct way            >>> s1
  
   set ([1, 2, 3])            >>> type (S1)            set  supported methods and operations:
  

3) Summary

    How to obtain use Help: Gets the properties and methods used by the object: Dir () Specific use of a method help: List.pop gets the document string for the callable object: Print obj.__doc__                containers, types, objects: 1, lists, tuples, dictionary literals can be distributed in multiple lines without line breaks, the last character can be followed by a comma (Jorian is not available) 2, all objects have a reference count (SYS module Getrefcount method); >>> Import sys >>> S1 set ([1, 2, 3]) >>> sy S.getrefcount (S1) View S1 reference count 3 3, lists, and dictionaries support two types of copy operations: Shallow copy and deep copy; Copy can be used for deep copy            The deepcopy () implementation in the module. 4, all objects in Python are "first class", which means that all objects named with the identifier have the same state, so that all objects can be named directly when the data is processed, 5, all sequences support iteration; (an ordered set of nonnegative integers) 6, all            Operations and methods supported by sequence: S[i] index s[i:j] Slice s[i:j:stride] extended slice      Len (s) min (s) max (s) sum (s) all (s) is true any (s)          Any true S1 + s2: Connection S1 * N: Duplicate membership judgment: obj in S1      Obj not in S1 7, variable sequence operation: S[index] = value element Assignment S[i:j] = t slice Assignment            S[i:j:stride] = T extended slice Assignment del S[index] element delete del s[i:j] Slice Delete Del s[i:j:stride] Extended slice Delete reference count and garbage collection: All objects have a reference count to assign a new name to an object or place it inside a container, and its reference count will increase When adding a del statement or re-assigning a value to a variable, its reference count is reduced by sys.getrefcount () to get the object's current reference count. A reference counter for an object is zeroed, and it is garbage collected Recovery
Related Article

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.