My Python self-learning Path 3: tuples and dictionary learning summary, the path to python

Source: Internet
Author: User

My Python self-learning Path 3: tuples and dictionary learning summary, the path to python

1. tuples

1. the Python tuples are similar to the list, except that the elements of the tuples cannot be modified.

The tuples use parentheses, And the list uses square brackets.

Creating tuples is simple. You only need to add elements in brackets and separate them with commas.

2. Create tuples

Tup = ("python", "java", "javascript", 1, 2, 3)

Tup1 = (1, 2, 3, 4, 5, 6)

Tup2 = ("a", "B", "c", "d ")

(1) Create null tuples

Tup = ()

(2) when there is only one tuple, it should end with a comma.

Tup = (30 ,)

3. Common Operations on tuples

Element index and Interception

Compared with the list, the append (), pop (), remove (), and insert () methods are used.

Cmp (tuple1, tuple2): Compares two tuples.

Len (tuple): calculates the length of the tuples.

Min (): returns the minimum value of the element.

Max (): returns the maximum value of the tuples.

Tuple (seq): converts a list to a tuple.

Ii. Dictionary

1. Dictionary

Dictionary is another variable container model that can store any type of objects and is also the unique ing type in Python.

In a ing object, the hash value (key, key) has a one-to-many relationship with the object (value, value), which is generally considered a variable hash table.

2. dictionary operations

(1) Create an empty dictionary

Dict = {}

(2) create a non-empty dictionary

Dict = {key1: value1, key2: value2, key3: value2}

Dict = {"naem": "laowang", "age": 38}

Dict =}

(3) basic dictionary operations

A. key Value of the access dictionary

Dict = {"name": "laowang", "age": "45", "address": "xibei "}

For key in dict. keys ():

Print key # output list ["name", "age", "address"]

B. Access the value of the dictionary

Dict [key] # Return the value corresponding to the key value

For example, dict ["name"] # returns the value of "laowang ".

C. Modify the dictionary

Dict = {"name": "laowang", "age": "23", "address": "xibei "}

Dict ["age"] = 34

Dict ["address"] = "huabei"

Output result:

Dict = {"name": "laowang", "age": 34, "address": huabei}

D. Delete dictionary elements

Dict = {"name": "laowang", "age": 34, "address": "xibei "}

Del dict ["name"] # delete an entry whose key is "name"

Print dict # The result is ["age": 34, "address": "xibei"]

Dict. clear () # clear all dictionary entries

Del dict # delete a dictionary

E. dictionary features

Dictionary values can be any python object without restrictions. They can be either standard objects or user-defined objects, but cannot be keys.

There are two important points to remember:

The same key cannot appear twice. If the same key is assigned twice during creation, the last value will be remembered,

The key must be unchangeable. Therefore, you can use numbers, strings, or tuples. Therefore, you cannot use a list.

(3) common dictionary Methods

Cmp (dict1, dict2) compares two dictionary elements

Len (dict) calculates the number of subcode elements, that is, the total number of keys.

Str (dict) outputs the string representation printed by the course.

Type (variable) returns the input variable type. If the variable is a dictionary, it returns the dictionary type.

Dict. clear ()

Dict. copy () returns the shortest copy of a dictionary.

Dict. fromkeys (seq [, val]) creates a new dictionary. The elements in sequence seq are used as Dictionary keys, and val is used as the initial values for multiple keys.

Dict. get (key, default = None) returns the specified value. If the value is not in the dictionary, the default value is returned.

Dict. has_key (key): If the key is returned in the dictionary dict, true is returned; otherwise, false is returned.

Dict. items () returns a list of (Key, value) tuples that can be traversed.

Dict. keys () returns all keys of a dictionary in the list.

Dict. setdefault (key, default = None) is similar to get (), but if it does not exist in the dictionary, a key is added and the value is set to default.

Dict. update (dict2) updates the key/value pairs of the dictionary dict2 to dict.

Dict. values () returns all values in the dictionary to the list.

Pop (key [, default]) deletes the value corresponding to the specified key in the dictionary. The returned value is the deleted Value.

Popitem () returns and deletes a pair of keys and values in the dictionary at random.

Common examples:

Has the following value set [ 11 , 22 , 33 , 44 , 55 , 66 , 77 , 88 , 99 , 90 ]. 66  To the first key of the dictionary. 66  To the value of the second key. That is :{ 'k1' : Greater 66  'k2' : Less 66, 'k3 ': equal to 66 }
list =[11,22,33,44,55,66,77,88,99,90]dict = {"k1":[],"k2":[],"k3":[]}for i  in list:    if i>66:        if dict.has_key("k1"):            dict["k1"].append(i)    elif i==66:        if dict.has_key("k3"):            dict["k3"].append(i)    else:        if dict.has_key("k2"):            dict["k2"].append(i)print dict

 

Dictionaries and lists are very similar. They are used in the same way. You can understand their differences.

I hope you can understand what is wrong when you are a newbie.

 

Related Article

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.