Python learning Note 4-dictionary and collection, and python learning note dictionary

Source: Internet
Author: User

Python learning Note 4-dictionary and collection, and python learning note dictionary

The dictionary is the only ing type in Python. The so-called ing refers to the sequence of the Data Type that contains the hash value (key) and the corresponding value (value. The dictionary is of a variable type. The data in the dictionary is unordered.

4.1.1 create and assign values to dictionaries

dict1={}dict2={'name':John,'age':24}

Use the dict () function to create a dictionary.

The dict () function accepts sequences, or keyword parameters as parameters to create dictionaries. If no parameter is provided, an empty dictionary is created.

Dict1 = dict ([['x', 1], ['y', 2]) # accept list as the parameter to create the dictionary dict2 = dict (x = 1.y= 2) # accept keyword parameters as parameters

Use the built-in method fromkeys () to create a "Default Dictionary". The keys in the dictionary correspond to the same value. If the value is not given, it is None.

dict1={}.fromkeys(('x','y'),1)dict1>>>{'y':1,'x':1}

4.1.2 worth accessing in the dictionary

Use the key in the dictionary to access the value.

info={'name':'bing','age':24,'sex':'male'}info['name']>>>'bing'

In Python, the access key is used by default to obtain the value.

info={'name':'bing','age':24,'sex':'male'}for key in info:    print 'key=%s,value=%s'%(key,info[key])>>>key='age',value='24'key='name',value='bing'key='sex',value='male'

4.1.3 update the dictionary

Update a dictionary includes the following operations: Add a "key-value" pair, delete dictionary elements, clear all or some entries in the dictionary, and modify the value of an element. The following is an example.

Info = {'name': 'bin', 'age': 24, 'sex ': 'male'} info ['name'] = 'xiaobing' # update an existing entry info ['addr '] = 'lanzhou' # Add a new entry

Deleting a dictionary usually refers to deleting a "key-value" pair. The del statement is used to delete the entire dictionary.

Del info ['name'] # Delete the entry info whose key is name in dict. clear () # clear all dictionary entries del info # Delete the entire dictionary info. pop ('name') # Return and delete the entry with the key name

4.2.1 ing Operators

1. dictionary search operator: []

Use dict [k] = n to assign n to the key k entry in dict; dict [k] to access the key k entry in dict.

2. member relationship OPERATOR: (in, not in)

dict1={'name':'bing','age':24,'sex':'male'}'name' in dict1>>>True'phone'in dict1>>>False

Note that in and not in are used only to check whether a key is in the dictionary.

4.3.1 related functions

1. dict () is used to create a dictionary. We will not repeat it later.

2. len (), return the dictionary length, that is, the number of "key-value" pairs in the dictionary

3. hash (): determines whether an object can be used as a dictionary key. When an object is passed to hash (), the hash value of this object is returned. Only this object can be hashed as a dictionary key.

4.4.1 built-in dictionary Methods

The following describes some built-in dictionary methods. For the rest, refer to the document if necessary.

1. dict. keys (), returns a list containing all keys in the dictionary.

2. dict. values (), returns a list containing all values in the dictionary.

3. dict. items () returns a list of elements consisting of (Key, value) tuples.

4. dict. clear (): delete all elements in the dictionary.

5. dict. copy () returns a copy of the Dictionary (Shortest copy ).

6. dict. update (dict2), and add the key-value pairs of the dictionary dict2 to dict.

4.5.1 descriptions of the dictionary types

1. One-to-multiple keys are not allowed, similar to the correspondence between two sets in the ing.

2. Keys must be Hash-able. All unchangeable types can be Hash, so they can be used as keys. A mutable type cannot be Hash-or cannot be used as keys, such as lists and dictionary types.

 

4.6 Set Data Type

In mathematics, a set is called a set of different elements. A set Member is called a set element. A collection object is a set of values that do not need to be hashed. The Set supports the in and not in check operators and uses len to get the set size (number of elements). However, the set cannot create indexes because the set does not need to be arranged. A set can be set or frozenset ).

4.6.1 create a set

A set can only be created using its factory method.

s=set('python')s>>>set(['y','o','n','t','p','h'])type(s)>>> <type,'set'>

4.6.2 operations on set Elements

Allows you to traverse and View Collection elements.

s=set('python')p in s>>>Truex in s>>>Falsefor i in s  print i>>>yontph

Add or delete a set element through the internal construction method and operator of the Set:

1. set. add () to add new elements to the set

2. set. update (), merging of Sets

3. set. remove (): Delete the elements in the set.

4.7 set member relationship operations

What really matters to a set is the relationship operation of the member relationship and the subset.

1. in, not in.

Returns True or False if an element is in a collection.

2. equivalence and non-equivalence = ,! =

Set equivalence means that each element in two sets is the same

3. Real subset and subset (<,<=)

4. Union

Symbol | or union () method.

5. Intersection

Symbol & or equivalent method intersection ()

6. difference set

Symbol-or equivalent method difference ()

 

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.