Python dictionary and Set learning Summary

  • 2020-06-07 04:47:47
  • OfStack

Mapping type:

Represents a collection of 1 arbitrary objects that can be indexed by another collection of almost arbitrary key values

Unlike sequences, maps are unordered and indexed by key

Any immutable object can be used as a dictionary key, such as a string, number, tuple, and so on

Lists, dictionaries, and tuples containing mutable objects cannot be used as keys

Referencing a key that does not exist throws an KeyError exception

1) the dictionary


 dict  { }   An empty dictionary 
      { key1:value1,key2:value2,... }
     Dictionaries are also called associative arrays or hash tables in other programming languages; 
   Access to elements through keys; Disordered set; Variable-type containers, variable-length, heterogeneous, nested 
   Supported operations: 
    len(D)            return D Number of projects in             
    D[k]             return D In the key k The value of the 
    D[k] = x           will D[k] The value of the set x          
          >>> d1 = {'x':1,'y':2,'z':3}
          >>> d1['x']
          1
          >>> d1['z']          By key index 
          3  
    del D[k]           from D Remove the D[k]
          >>> del d1['x']
          >>> d1
          {'y': 2, 'z': 3}
    k in D            if k is D , returns the value of True
    Supported methods: 
    D.clear()           Clear all elements 
    D.copy()           copy 1 A copy of the 
          >>> d1 = {'x':1,'y':2,'z':3}
          >>> id(d1)
          45320640
          >>> d2 = d1.copy()         Deep copy 
          >>> id(d2)
          45997776      
          >>> d3 = d1             A shallow copy 
          >>> id(d3)
          45320640              d1 , d3 Point to the same 1 Object, d2 Pointing to the other 1 object 
    D.get(k[,d])         Gets the value of the corresponding key and returns if none exists d( The default is empty )
          >>> d1.get('y')
          2
    D.has_key(k)         Whether a key value exists, returns True or False.( Only in the pyhton2 The use of )
    D.items()           convert (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'                  Keys, not values, are saved !!!
    D.values()          List of values 
          >>> d1.values()
          [2, 1, 3]
    D.keys()           List of key 
          >>> d1.keys()
          ['y', 'x', 'z']
    D.pop(k[,d])         Pops up the specified key value, or raises an exception if not specified 
          >>> d1.pop()
          TypeError: pop expected at least 1 arguments, got 0
          >>> 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'         Is a space - time exception 
          >>> d1
          { }
    D.update(m)           Merge the dictionary 
          >>> d1 = { 'x':1,'y':2,'z':3 }
          >>> d2={'c':'hello','y':66}
          >>> d1.update(d2)
          >>> d1
          {'y': 66, 'x': 1, 'c': 'hello', 'z': 3}        If the key exists, it will be overwritten; if not, it will be added   
    D.iteritems()           return 1 Three iterator objects 
          >>> d1 = { 'x':1,'y':2,'z':3 }
          >>> i1 = d1.iteritems()
          >>> i1.next()           use next The method traverses each 1 An element 
          ('y', 2)
          >>> i1.next()
          ('x':1)
          >>> i1.next()
          ('z':3)
          >>> i1.next()
          StopIteration           There is no restart after the traversal 
    D.iterkeys()    ->   an iterator over the keys of D
          >>> i2 = d1.iterkey()
          >>> i2.next()
          'y'
    D.itervalues()   ->   an iterator over the values of D
          >>> i3 = d1.iterkey()
          >>> i3.next()
          2
    D.viewvalues()                Returns a collection - like dictionary ( The value of )
          >>> d1.viewvalues()
          dict_values([2, 1, 3])
    D.viewitems()    ->   a set-like object providing a view on D's items( Key/value pair )
          >>> 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)        Definition dictionary 1 Kind of way 
          >>> d2
          {'y': 2, 'x': 1, 'z': 3}
   Supplement: zip   Returns a list of tuples 
      >>> zip('xyz','123')
      [('x', '1'), ('y', '2'), ('z', '3')]      11 Corresponding generation list 
      >>> zip('xyzm','123')
      [('x', '1'), ('y', '2'), ('z', '3')]       The redundant items are discarded 
      >>> zip('xyz','123','qer')
      [('x', '1', 'q'), ('y', '2', 'e'), ('z', '3', 'r')]        
      >>> dict(zip('xyz','123'))            To construct a dictionary 
      {'y': '2', 'x': '1', 'z': '3'}

2) set


 Disordered arrangement, hashing; 
  Support for set relationship testing 
     Membership test: 
      in
      not in
       The iteration 
  Not supported: index, element fetch, slice 
  Type of collection:  set()  frozenset()
         variable      immutable 
  There is no specific syntax format and it can only be created through factory functions   
    Ex. : 
      >>> s1=set(1,2,3)                    
      TypeError: set expected at most 1 arguments, got 3        Wrong way 
      >>> s1 = set([1,2,3])                       Right way 
      >>> s1
      set([1, 2, 3])
      >>> type(s1)
      set

Supported methods and actions:

3) summary


  How to get help: 
     Gets the properties and methods the object supports using: dir()
     Specific use of a method: help(list.pop)
     Gets the document string of the callable object: print obj.__doc__
   Containers, types, objects: 
    1 , lists, tuples, dictionary literals can be distributed in multiple lines without newline characters, and finally 1 Two characters can be followed by a comma ( If empty, do not use )  
    2 , all objects have reference counts (sys In the module getrefcount methods );
        >>> import sys
        >>> s1
        set([1, 2, 3])
        >>> sys.getrefcount(s1)          To view s1 Reference count of 
        3
    3 , lists, and dictionaries all support two types of replication: shallow and deep; Deep replication is available copy In the module deepcopy() The implementation. 
    4 , Python All objects in the 1 ", which means that all objects named with an identifier have the same state. Thus, being able to name all objects can be processed directly as data; 
    5 , all sequences support iteration; ( An ordered set of nonnegative integers )
    6 , operations and methods supported by all sequences: 
      s[i]       The index         s[i:j]    slice       
      s[i:j:stride]   Extended slice       len(s)
      min(s)     max(s)       sum(s)
      all(s)      All for true     any(s)    Any for true
      s1 + s2:  The connection             s1 * N:  repeat 
       Membership judgment: 
        obj in s1
        obj not in s1
    7 , operation of variable sequence: 
      s[index] = value     Elements of the assignment 
      s[i:j] = t        Slice assignment 
      s[i:j:stride] = t     Extended slice assignment 
      del s[index]       Element to delete 
      del s[i:j]        Slicing to delete 
      del s[i:j:stride]     Extended slice deletion 
     Reference counting and garbage collection: 
       All objects have reference counts 
         Assign objects 1 Two new names or put them in 1 The reference count is increased for each container 
         with del When a statement or variable is re-assigned, its reference count is reduced 
        sys.getrefcount() You can get the current reference count of an object 
      1 When the reference counter returns to zero, it is collected by the garbage collection mechanism 

Related articles: