Dictionaries and collections in Python

Source: Internet
Author: User

Dictionaries and collections in Python

映射类型:    表示一个任意对象的集合,且可以通过另一个几乎是任意键值的集合进行索引    与序列不同,映射是无序的,通过键进行索引        任何不可变对象都可用作字典的键,如字符串、数字、元组等        包含可变对象的列表、字典和元组不能用作键        引用不存在的键会引发KeyError异常

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 '] by key index3 del d[k] remove d[k from D]>>> del d1[' X ']>>> D1 {' Y ':2,' Z ':3} kIn D if K is the value in D, returns true for supported methods: 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, and 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 () Convert to (key,value) a list of tuples>>> 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 ' holds the key, 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]) pops the specified key value, which will trigger an exception if not specified>>> D1.pop ()Typeerror:pop expected at least1 arguments, got0>>> D1.pop (' X ')1>>> D1 {' Y ':2,' Z ':3} d.popitem () Random Popup>>> D1.popitem () (' Y ',2)>>> D1.popitem () (' Z ',3)>>> D1.popitem ()Keyerror:' Popitem (): Dictionary is empty exception>>> D1 {} d.update (m) merged dictionary>>> D1 = {' X ':1,' Y ':2,' Z ':9 ·>>> d2={C:' Hello ',' Y ':66}>>> D1.update (D2)>>> D1 {' Y ':46n' X ':1,C:' Hello ',' Z ':3} If the key exists, it will be overwritten, and the addition of D.iteritems () does not exist to return an iterator object>>> D1 = {' X ':1,' Y ':2,' Z ':3}>>> i1 = D1.iteritems ()>>> I1.next () uses the next method to iterate through each element (' Y ',2)>>> I1.next () (' X ':1)>>> I1.next () (' Z ':3)>>> I1.next () stopiteration after traversal does not restart 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 ()>>> 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 '])>>> 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>>> Zip (' XYZ ',' 123 ') [(' X ',' 1 '), (' Y ',' 2 '), (' Z ',' 3 ')] One by one corresponds 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 ', >>> dict (Zip ( ' xyz ',  ' 123 ')) Construct Dictionary { ' y ' :  ' 2 ',  ' x '  ' 1 ',  ' z ' :  ' 3 '}      

2) Collection

Unordered arrangement, hash, support for set relationship Test membership test:In notIn iterations not supported: Index, element Fetch, tile collection type:set () Frozenset () mutable immutable no specific syntax format can only be created by Factory function Example: >>> s1=Set (
        
         1,
         2,3) TypeError: set expected at the most 1 arguments, got 3 error mode >>> S1 = set ([ C11>1,2,3]) correct way >>> S1 set ([1, 2, 3]) >>> type (S1) set Supported methods and actions:                
         

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__ container , type, object:1, list, tuple, dictionary literal can be distributed in multiple lines without line break, the last character can be followed by a comma (Jorian is not available)2. All objects have reference count (Getrefcount method in sys module); >>>Import sys >>> S1 set ([1,2,3]) >>> Sys.getrefcount (S1) View reference count for S133. Both lists and dictionaries support two types of copy operations: Shallow copy and deep copy, and deep copy can be implemented using the Deepcopy () in the Copy module.4, all objects in Python are "first class", which means that all objects named with an identifier have the same state, so that all objects can be named directly when the data is processed;5. All sequences support iteration; (ordered set of nonnegative integers)6, operations and methods supported by all sequences: S[i] Index S[i:j] slice s[ I:j:stride] Extended slice len (s) min (s) max (s) sum (s) all (s) for true Any (s) is true S1 + S2: Connection S1 * N: Repeat Member relationship 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 assign a new name to an object or place it inside a container, and its reference count will increase When you use a DEL statement or reassign a value to a variable, its reference count is reduced by sys.getrefcount () to get the object's current reference count. The reference counter of an object is zeroed, and it is reclaimed by the garbage collection mechanism     

Dictionaries and collections in Python

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.