Python Tuples and dictionaries

Source: Internet
Author: User
This article shares a detailed introduction to python Tuples and dictionaries. 1. tuples

1. expression of tuples

(1,2,3,4)('olive',123)("python",)

Create tuples:

a=tuple((1,2,3,))b=("python",)

2. feature attributes of tuples

Class tuple (object): "tuple ()-> empty tuple (iterable)-> tuple initialized from iterable's items If the argument is a tuple, the return value is the same object. "def count (self, value): # real signature unknown; restored from _ doc _" "T. count (value)-> integer -- return number of occurrences of value "" return 0 def index (self, value, start = None, stop = None): # real signature unknown; restored from _ doc _ "T. index (value, [start, [stop])-> integer -- return first index of value. raises ValueError if the value is not present. "" return 0 def _ add _ (self, * args, ** kwargs): # real signature unknown "Return self + value. "pass def _ contains _ (self, * args, ** kwargs): # real signature unknown" Return key in self. "pass def _ eq _ (self, * args, ** kwargs): # real signature unknown" Return self = value. "pass def _ getattribute _ (self, * args, ** kwargs): # real signature unknown" Return getattr (self, name ). "pass def _ getitem _ (self, * args, ** kwargs): # real signature unknown" "Return self [key]. "pass def _ getnewargs _ (self, * args, ** kwargs): # real signature unknown pass def _ ge _ (self, * args, ** kwargs): # real signature unknown "" Return self> = value. "pass def _ gt _ (self, * args, ** kwargs): # real signature unknown" Return self> value. "pass def _ hash _ (self, * args, ** kwargs): # real signature unknown" Return hash (self ). "pass def _ init _ (self, seq = (): # known special case of tuple. _ init _ "tuple ()-> empty tuple (iterable)-> tuple initialized from iterable's items If the argument is a tuple, the return value is the same object. # (copied from class doc) "pass def _ iter _ (self, * args, ** kwargs ): # real signature unknown "" Implement iter (self ). "pass def _ len _ (self, * args, ** kwargs): # real signature unknown" Return len (self ). "pass def _ le _ (self, * args, ** kwargs): # real signature unknown" Return self <= value. "pass def _ lt _ (self, * args, ** kwargs): # real signature unknown" Return self
 
  

3. Introduction to some feature attributes of tuples

Tuples have great similarity with lists, but elements of tuples cannot be modified. Therefore, many lists do not have function tuples.

1) count (self, value ):

Count the number of value elements in the tuples and return an int value.

A = (, 1, 2,) B =. count (1) print (a, type (a) print (B, type (B) # run the result (1, 2, 3, 4, 1, 2, 3, 1, 2)
   
    
3
    
     
Demo
    
   

2) index (self, value, start = None, stop = None ):

Index to find the first position of the value element in the tuples. the start and stop parameters are the start and end positions of the query. the default value is None. an int value is returned. if this element is not included in the query, valueError: 'F' is not in tuple is returned.

A = (, 1, 2,) B =. index (3) print (a, len (a) print (B, type (B) # run the result (1, 2, 3, 4, 1, 2, 3, 1, 2) 92
   
    
Demo
   

3) add (self, * args, ** kwargs ):

Add a new element to the tuples. The new elements must be added as tuples to generate a new one.

A = (1, 2, 3, 4) B =. _ add _ (5, 1) # print (a, type (a) print (B, type (B )) # running result (1, 2, 3, 4)
   
    
(1, 2, 3, 4, 5, 1)
    
     
Demo
    
   

4) contains (self, * args, ** kwargs ):

Returns a boolean value to determine whether a tuple contains an element.

A = (, 1, 2,) B =. _ contains _ (2) c =. _ contains _ (5) print (a) print (B) print (c) # running result (1, 2, 3, 4, 1, 2, 3, 1, 2) TrueFalsedemo

II. dictionary

1. dictionary expression

{"name":"olive","age":18}

Create a dictionary:

a={"name":"olive","age":18}b=dict({"name":"lusi","age":18})

2. dictionary function attributes

class dict(object):    """    dict() -> new empty dictionary    dict(mapping) -> new dictionary initialized from a mapping object's        (key, value) pairs    dict(iterable) -> new dictionary initialized as if via:        d = {}        for k, v in iterable:            d[k] = v    dict(**kwargs) -> new dictionary initialized with the name=value pairs        in the keyword argument list.  For example:  dict(one=1, two=2)    """    def clear(self): # real signature unknown; restored from __doc__        """ D.clear() -> None.  Remove all items from D. """        pass    def copy(self): # real signature unknown; restored from __doc__        """ D.copy() -> a shallow copy of D """        pass    @staticmethod # known case    def fromkeys(*args, **kwargs): # real signature unknown        """ Returns a new dict with keys from iterable and values equal to value. """        pass    def get(self, k, d=None): # real signature unknown; restored from __doc__        """ D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None. """        pass    def items(self): # real signature unknown; restored from __doc__        """ D.items() -> a set-like object providing a view on D's items """        pass    def keys(self): # real signature unknown; restored from __doc__        """ D.keys() -> a set-like object providing a view on D's keys """        pass    def pop(self, k, d=None): # real signature unknown; restored from __doc__        """        D.pop(k[,d]) -> v, remove specified key and return the corresponding value.        If key is not found, d is returned if given, otherwise KeyError is raised        """        pass    def popitem(self): # real signature unknown; restored from __doc__        """        D.popitem() -> (k, v), remove and return some (key, value) pair as a        2-tuple; but raise KeyError if D is empty.        """        pass    def setdefault(self, k, d=None): # real signature unknown; restored from __doc__        """ D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D """        pass    def update(self, E=None, **F): # known special case of dict.update        """        D.update([E, ]**F) -> None.  Update D from dict/iterable E and F.        If E is present and has a .keys() method, then does:  for k in E: D[k] = E[k]        If E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v        In either case, this is followed by: for k in F:  D[k] = F[k]        """        pass    def values(self): # real signature unknown; restored from __doc__        """ D.values() -> an object providing a view on D's values """        pass    def __contains__(self, *args, **kwargs): # real signature unknown        """ True if D has a key k, else False. """        pass    def __delitem__(self, *args, **kwargs): # real signature unknown        """ Delete self[key]. """        pass    def __eq__(self, *args, **kwargs): # real signature unknown        """ Return self==value. """        pass    def __getattribute__(self, *args, **kwargs): # real signature unknown        """ Return getattr(self, name). """        pass    def __getitem__(self, y): # real signature unknown; restored from __doc__        """ x.__getitem__(y) <==> x[y] """        pass    def __ge__(self, *args, **kwargs): # real signature unknown        """ Return self>=value. """        pass    def __gt__(self, *args, **kwargs): # real signature unknown        """ Return self>value. """        pass    def __init__(self, seq=None, **kwargs): # known special case of dict.__init__        """        dict() -> new empty dictionary        dict(mapping) -> new dictionary initialized from a mapping object's            (key, value) pairs        dict(iterable) -> new dictionary initialized as if via:            d = {}            for k, v in iterable:                d[k] = v        dict(**kwargs) -> new dictionary initialized with the name=value pairs            in the keyword argument list.  For example:  dict(one=1, two=2)        # (copied from class doc)        """        pass    def __iter__(self, *args, **kwargs): # real signature unknown        """ Implement iter(self). """        pass    def __len__(self, *args, **kwargs): # real signature unknown        """ Return len(self). """        pass    def __le__(self, *args, **kwargs): # real signature unknown        """ Return self<=value. """        pass    def __lt__(self, *args, **kwargs): # real signature unknown        """ Return self
   
     size of D in memory, in bytes """        pass    __hash__ = Nonedict
   

3. Introduction to some feature attributes of the dictionary
1) clear (self ):

Clear all elements in the dictionary.

A = {"name": "olive", "age": 18} B = a. clear () print (a) print (B) # running result {} None

2) copy (self ):

Copy a tuple, which is equivalent to a small copy.

A = {"name": "olive", "age": 18} B =. copy () print (a, id (a), id ("name") print (B, id (B), id ("name ")) # assign c = {"name": "lusi", "age": 18} d = cprint (c, id ("name") print (d, id ("name") # shy copy e = {"name": "shy", "age": 18} f = copy. copy (e) print (e, id (e), id ("name") print (f, id (f), id ("name ")) # running result {'name': 'live', 'age': 18} 2915224 2019840 {'name': 'live', 'age ': 18} 2915304 2019840 {'name': 'lusi', 'age': 18} 2019840 {'name': 'lusi', 'age ': 18} 2019840 {'name': 'shy', 'age': 18} 5584616 2019840 {'name': 'shy', 'age': 18} 5586056 2019840

3) fromkeys (* args, ** kwargs): [fromkeys (seq, value = None )]

Create a new dictionary, which uses seq as the dictionary's keys (key) and value as the dictionary's value. The default value is None. It is suitable for creating a dictionary with the same value.

A = {"hunan": "changsha", "guangdong": "guangzhou", "jiangsu": "nanjing", 'hubei': "wuhan"} B = dict. fromkeys (a, "good") c = dict. fromkeys (["a", "B", "c"], "abc") d = dict. fromkeys ("abcc") print (a) print (B) print (c) print (d) # run the result {'guangdong': 'guangzhou', 'hubei ': 'wuhan', 'hunanc': 'changsha', 'jiangsu': 'nanjing'} {'hubei': 'Good', 'guangdong': 'Good ', 'hunanc': 'Good', 'jiangsu': 'Good'} {'C': 'ABC', 'B': 'ABC', 'A': 'ABC' } {'C': None, 'B': None, 'A': None} # The string c given by seq is repeated, but only one key is created.

4) get (self, k, d = None ):

Obtain the value of k in the dictionary. if k is not included in the dictionary, the value d is given. the default value d is None.

A = {"a": 1, "B": 2, "c": 3, "d": 4} B =. get ("a") c =. get ("e") d =. get ("e", 5) print (a) print (B) print (c) print (d) # run the result {'B': 2, 'A': 1, 'C': 3, 'D': 4} 1None5

5) items (self ):

A dictionary traversal method combines every pair of key and value in the dictionary into a tuple, and puts these tuples in a list-like dict_items to return.

A = {"a": 1, "B": 2, "c": 3, "d": 4} B =. items () print (a) print (B, type (B) # run the result {'D': 4, 'C': 3, 'A': 1, 'B': 2} dict_items ([('D', 4), ('C', 3), ('A', 1), ('B ', 2)])
   

6) keys (self ):

A method that traverses the dictionary key keys and returns a list-like dict_keys, which is the same as the items method.

A = {"a": 1, "B": 2, "c": 3, "d": 4} B =. keys () print (a) print (B, type (B) # run the result {'B': 2, 'A': 1, 'C': 3, 'D': 4} dict_keys (['B', 'A', 'C', 'D'])
   

7) values (self ):

A method that traverses dictionary value values and returns a list-like dict_values, which is the same as the items method.

A = {"a": 1, "B": 2, "c": 3, "d": 4} B =. values () print (a) print (B, type (B) # run the result {'C': 3, 'D': 4, 'B': 2, 'A': 1} dict_values ([3, 4, 2, 1])
   

8) pop (self, k, d = None ):

Similar to the get method, except that get is used to obtain the value of k in the dictionary and pop is used to retrieve the value of k in the dictionary. If the dictionary does not contain the key k and d is not the default value, the obtained value is the d VALUE. if d is the default value of None, the KeyError is returned.

A = {"a": 1, "B": 2, "c": 3, "d": 4} B =. pop ("a") c =. pop ("e", "five") print (a) print (B, type (B) print (c, type (c) # run the result {'C ': 3, 'D': 4, 'B': 2} 1
   
    
Five
    
   

9) popitem (self ):

A group of key values are randomly taken from the dictionary and a new tuple is returned. If the dictionary has no key value, KeyError is returned.

A = {"a": 1, "B": 2, "c": 3, "d": 4} B =. popitem () print (a) print (B, type (B) # run the result {'D': 4, 'B': 2, 'A ': 1} ('C', 3)
   

10) setdefault (self, k, d = None ):

Obtain the key-k value from the dictionary. if the dictionary contains the key-k value, the function is basically the same as that of get. if the dictionary does not contain the key-k value, add an initial key-value pair with k in the original dictionary and return value d.

A = {"a": 1, "B": 2, "c": 3, "d": 4} B =. setdefault ("a") c =. setdefault ("e") d =. setdefault ("f", 6) print (a) print (B) print (c) print (d) # run the result {'F': 6, 'C': 3, 'A': 1, 'E': None, 'B': 2, 'D': 4} 1None6

11) update (self, E = None, ** F ):

Adds an element to the dictionary without returning a value. Usage: dict. update (dict2 ).

A = {"a": 1, "B": 2, "c": 3, "d": 4} B =. update ({"e": 5}) print (a) print (B) # run the result {'C': 3, 'B': 2, 'D': 4, 'A': 1, 'E': 5} None

12) contains (self, * args, ** kwargs ):

Returns a boolean value if the list contains a key-value pair. Usage: dict. contains (keys ).

A = {"a": 1, "B": 2, "c": 3, "d": 4} B =. _ contains _ ("a") print (a) print (B) # running result {'a': 1, 'D': 4, 'C': 3, 'B': 2} True

13) delitem (self, * args, ** kwargs ):

Deletes a key-value pair in the dictionary and does not return a value. Usage: dict. delitem (keys ).

A = {"a": 1, "B": 2, "c": 3, "d": 4} B =. _ delitem _ ("a") print (a) print (B) # running result {'C': 3, 'B': 2, 'D ': 4} None

The above is a detailed description of python Tuples and dictionaries. For more information, see other related articles in the first PHP community!

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.