Python Learning note Four--dictionaries and collections

Source: Internet
Author: User

A dictionary is the only type of mapping in Python. A mapping is a sequence of the data type that contains the hash value (key) and its corresponding value (value). A dictionary is a mutable type. The data in the dictionary is unordered.

Creation and assignment of 4.1.1 dictionaries

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

Use the Dict () function to create a dictionary.

The Dict () function accepts a sequence, or the keyword parameter creates a dictionary as a parameter. Creates an empty dictionary if no arguments are provided.

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

Use the built-in method Fromkeys () to create a "default dictionary" with keys that correspond to the same values and none if the value is not given.

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

The 4.1.2 Dictionary is worth visiting

The value is accessed through the keys in the dictionary.

info={'name':'Bing','age': 24, ' Sex ':'male'}info['name' ]>>>'Bing'

The default in Python is to get the value by accessing the key.

info={'name':'Bing',' Age': 24,'Sex':'male'} forKeyinchInfo:Print 'key=%s,value=%s'%(Key,info[key])>>>Key=' Age', value=' -'Key='name', value='Bing'Key='Sex', value='male'

4.1.3 Updating dictionaries

Updates to the dictionary include the following operations, adding a "key-value" pair, deleting the dictionary element, clearing all or individual entries in the dictionary, and modifying the value of an element. The following examples illustrate.

info={'name':'Bing',' Age': 24,'Sex':'male'}info['name']='xiaobing'#Update an existing entryinfo['Addr']='Lanzhou'#Add new entry

Deleting a dictionary generally means deleting a "key-value" pair, and deleting the entire dictionary will use the DEL statement.

del info['name'# Delete entry in Dict key for name Info.clear ()        #  Empty dictionary all entries del info             # Delete entire dictionary info.pop (' name ')#  Returns and deletes an entry with the key name

4.2.1 Operator for map type

1. Dictionary lookup operator: []

Using the method Dict[k]=n, assign n to the entry with the key k in Dict, Dict[k], and access the entry with the key k in the Dict.

2. Member relationship operator: (In,not in)

dict1={'name':'Bing',' Age': 24,'Sex':'male'}'name' inchDict1>>>True'Phone'inchDict1>>>false

It is important to note that in and not are only used as a check for a key in the dictionary.

4.3.1 correlation function

1, Dict (), used to create a dictionary, said not to repeat the previous.

2, Len (), returns the dictionary length, which is the number of "key-value" pairs in the dictionary

3, hash (), determine whether an object can do dictionary keys. When an object is passed to a hash (), the hash value of the object is returned, and only the object is hashed to be used as the dictionary key.

The built-in method of 4.4.1 Dictionary

Some of the built-in methods of the dictionary are mentioned below, and the rest of the documentation is consulted if necessary.

1, Dict.keys (), returns a list that contains all the keys in the dictionary.

2, Dict.values (), returns a list that contains all the values in the dictionary.

3, Dict.items (), returns a list of elements (the key, value) tuple as an element.

4, Dict.clear (), delete all the elements in the dictionary.

5, Dict.copy (), returns a copy of the dictionary (shallow copy).

6, Dict.update (DICT2), add the dictionary dict2 key-value pairs to the Dict.

4.5.1 Some descriptions of the keys in the dictionary

1, the key does not allow a one-to-many, similar mapping in the corresponding relationship between two sets.

2, the key must be hashed, all immutable types are hashed so it can be used as a key, mutable type is not a hash is not a key, such as a list, dictionary type.

4.6 Aggregate data types

The collection (set) member is referred to as a collection element, which is mathematically referred to as a collection of different elements. A collection object is a set of values that do not need to be hashed. The collection supports the In,not in check operator, which uses Len to get the collection size (number of elements), but the collection cannot create an index because the collection does not have to be arranged. There are two different types of collections, mutable collections (set) and immutable collections (Frozenset).

Creation of the 4.6.1 collection

A collection can only be created by its factory method

s=Set('python') s>>>Set(['y','o','N','T','P','h']) type (s)>>> <type,'Set'>

4.6.2 operation of the collection element

Can traverse to view collection elements

s=Set('python' in s>>>in  s>>>False for in s  print i>>> yontph

Adding or removing collection elements through the collection's built-in methods and operators:

1, Set.add (), adding new elements to the collection

2, Set.update (), merging of collections

3, Set.remove (), delete the elements in the collection

4.7 Set-member-relationship operations

What really matters for a collection is the relationship operation of the membership and the subset.

1. member relationship In,not in.

Determines whether an element is in a collection and returns True or false.

2, equivalence and non-equivalence ==,!=

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

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

4, and set

Symbol | or union () method.

5. Intersection

Symbol & or Equivalent method intersection ()

6. Difference Set

Symbol-or equivalent method difference ()

Python Learning note Four--dictionaries and collections

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.