Python Learning Note 3 (tuples, dictionaries)

Source: Internet
Author: User
Tags hashable

There are three built-in data types in Python. Dictionary (dictionary), list, and tuple (tuples).

Meta-group (tuple)

Read-only list (the value of the list can be modified, not the Tuple)

Tuples are similar to lists, except that elements of tuples cannot be modified.

Tuples use parentheses, and the list uses square Brackets.

Tuple creation is simple, just add elements in parentheses and separate them with Commas.

The following example:

Tup1 = (' Physics ', ' Chemistry ', 1997, 2000)

tup2 = (1, 2, 3, 4, 5)

Tup3 = "a", "b", "c", "d"

Create an empty tuple

Tup1 = ()

When you include only one element in a tuple, you need to add a comma after the element

Tup1 = (50,)

Tuples are similar to strings, and subscript indexes start at 0 and can be intercepted, combined, and so On.

accessing tuples

Tuples can use the subscript index to access the values in the tuple, as in the following example:

Tup1 = (' Physics ', ' Chemistry ', 1997, 2000)

tup2 = (1, 2, 3, 4, 5, 6, 7)

Print ("tup1[0]:", Tup1[0])

Print ("tup2[1:5]:", Tup2[1:5])

The result of the above example Output:

Tup1[0]: Physics

Tup2[1:5]: [2, 3, 4, 5]

modifying tuples

The element values in the tuple are not allowed to be modified, but we can combine the tuples with the following example:

Tup1 = (12, 34.56)

TUP2 = (' ABC ', ' XYZ ')

The following modifications to tuple element operations are Illegal.

tup1[0] = 100

To create a new tuple

Tup3 = Tup1 + tup2

Print (tup3)

The result of the above example Output:

(34.56, ' abc ', ' XYZ ')

Delete a tuple

element values in tuples are not allowed to be deleted, but we can use the DEL statement to delete an entire tuple, as in the following example:

Tup = (' Physics ', ' Chemistry ', 1997, 2000)

Print (tup)

Del Tup

Print "after deleting tup:"

Print (tup)

Tuple operators

As with strings, you can use the + and * numbers to perform operations between Tuples. This means that they can be combined and copied, and a new tuple is generated after the Operation.

Python expressions

Results

Describe

Len ((1, 2, 3))

3

Count the number of elements

(1, 2, 3) + (4, 5, 6)

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

Connection

[' hi! '] * 4

(' hi! ', ' hi! ', ' hi! ', ' hi! ')

Copy

3 in (1, 2, 3)

True

Whether the element exists

For x in (1, 2, 3): print x,

1 2 3

Iteration

Tuple index, Intercept

Because tuples are also a sequence, we can access the elements at the specified location in the tuple, or we can intercept an element in the index as Follows:

Meta-group:

L = (' spam ', ' spam ', ' spam! ')

Python expressions

Results

Describe

l[2]

' spam! '

Reading a third element

l[-2]

' Spam '

Read the second last element of the inverse

l[1:]

[' Spam ', ' spam! ']

Intercepting elements

No close delimiter

Arbitrarily unsigned objects, separated by commas, are tuples by default, as in the following example:

#!/usr/bin/python

print ' ABC ', -4.24e93, 18+6.6j, ' xyz ';

x, y = 1, 2;

Print "Value of x, y:", x, y;

The above example allows the Result:

abc-4.24e+93 (18+6.6j) XYZ

Value of x, Y:1 2

Tuple built-in functions

The Python tuple contains the following built-in functions

Serial number

Methods and descriptions

1

cmp (tuple1, tuple2)
Compares two tuple elements.

2

len (tuple) The
counts the number of tuple elements.

3

max (tuple) The
returns the maximum value of the element in the Tuple.

4

min (tuple) The
returns the minimum value of the element in the Tuple.

5

tup Le (seq)
Converts the list to a tuple.

Dictionary ( dictionary )

The dictionary dict, which is the only standard mapping type of python, is also built into the Python interpreter.

Mapping object maps a hash value (hashablevalue) to an arbitrary object.

What is a hash

An object is a hash (hashable), which is the value returned by the object in its lifetime with a constant hash value (hashvalue), which is the __hash__ () method.

All immutable (immutable) built-in objects are hashable, such as String,tuple. All mutable (mutable) built-in containers are not hashable, such as List,dict (that is, there is no __hash__ () method). and all custom class (use-definedclass) objects are hashed (hashable) and can only be equal to themselves, whose hashvalue is the value of its ID (object), where the ID () is a built-in function, The CPython implements the address of the object in memory when it is Taken.

The key of the dictionary dictionary must be hashed, so tuple,string can do the key, and list cannot do the KEY.

Dict itself is a class

Class Dict (mapping)

In Layman's terms, A dictionary is nothing more than a lot of data, but it has a directory where you can find detailed information about it with a simple value in the Directory. In other words, a table of contents is a special indication of the content, that is, each field in the table of contents, will have the details corresponding to it in the Content. That is, each information in the directory is unique and does not conflict with other information in the Directory.

The dictionary in Python is not just for storing strings. The value of dictionary can be any data type, including strings, integers, objects, and even other dictionary. In a single dictionary, the value of dictionary does not need to be all the same data type and can be mixed and matched as Needed. But Python's key is more rigorous, they can be strings, integers (i know only these two). You can also mix and match key data types in a dictionary.

Define Dictionary

DIC = {"server": "apache", "database": "master"} Each element is a key-value pair, and the entire element set is enclosed in curly Braces. The value can be referenced by key, but it cannot be obtained by a Value. So the value of d["server"] is ' Apache '.

Modify Dictionary

There is no duplicate key in a dictionary, but we can assign a value to an existing key, overwriting the original Value. For example, I want to change the value of "server" in dictionary dic to "weblogic", dic["server" = "weblogic".

Add Key-value

Adding a Key-value pair is simple, for example: I want to add user= ' root ' key-value pair in dictionary, dic["user"] = "root".

Dictionary Common Methods In:

Len (a)

Get the number of elements in dictionary a

a[k]

Gets the value corresponding to the key k in the dictionary a

a[k] = V

Sets the value corresponding to the key k in dictionary A to be V

Del a[k]

Use key to remove independent elements from a dictionary. For example, delete user= ' root ' in dictionary dic: del dic["user"]

A.clear ()

Clears all elements from a dictionary. For example, remove all elements in dictionary dic: dic.clear ()

A.copy ()

Get a copy of a dictionary

K in a

The key k in the dictionary is returned true, and no returns false

K Not in a

The key k does not exist in the dictionary and returns true, otherwise false

A.has_key (k)

Determine if the dictionary a contains key k

A.items ()

Get the Key-value pair list in dictionary a

A.keys ()

Get the list of the dictionary a Middle key

A.update ([b])

Update a dictionary from the B dictionary, update if the key is the same, append if not present in A.

A.fromkeys (seq[, Value])

Creates a new dictionary with keys from SQL and values from value

A.values ()

Get a list of the values in dictionary a

A.get (k[, X])

The value of the key k is removed from dictionary a, and if not, an X is returned

A.setdefault (k[, X])

Set the value of the key to K to the default value of X. If k is present in dictionary a, the value of K is returned, if it does not exist, a k-x key-value pair is added to the dictionary and the value x is returned

A.pop (k[, X])

Remove the value of the key k in dictionary A and delete it from dictionary a, or return the value x if there is no key k in dictionary a

A.popitem ()

Remove the key-value pair from dictionary A and delete it from dictionary a

A.iteritems ()

Returns an iterator for all key-value pairs in dictionary A.

A.iterkeys ()

Returns an iterator for all keys in Dictionary A.

A.itervalues ()

Returns an iterator for all values of dictionary A.

The key value in the dictionary is Case-sensitive. And you cannot have duplicate key values in the same dictionary. also, There is no concept of element order in Dictionary.

Dictionary two major features: unordered, key unique

Create a dictionary
1
Dic={"name": "liu", "age": "all", "hobby": "python",}
DIC = dict ((' name ', ' Liu '), (' age ', ' 23 '),))
Print (dic)
2
DIC = dict ([[' name ', ' Liu '],[' age ', ' 23 '],])
Print (dic)
operation of the dictionary
Increase
1
dic={' name ': ' Liu '}
dic[' Age ']=3
Print (dic)
2 If the key is not joined, the return value is increased by the corresponding value
dic={' name ': ' Liu '}
A=dic.setdefault (' Age ', 34)
Print (dic)
Print (a)
If the key is not, then no modification is made, The return value is the original dictionary
dic={' name ': ' Liu '}
A=dic.setdefault (' name ', 34)
Print (dic)
Print (a)
3.update dic changes, Dic1 unchanged
dic={' name ': ' Liu '}
dic1={' Age ': 23}
Dic.update (dic1)
Print (dic)
Print (dic1)

Check
Find by Key
dic={' name ': ' Liu ', ' age ': 45}
Print (dic[' name '])
Print (list (dic.keys ())) look up all the keys in the dictionary
Dic.values () Check the values in the dictionary
Dic.item all of the key values to be taken in tuples
Change
dic={' name ': ' Liu '}
dic[' name ']= ' Alex '
Print (dic)
Delete
dic={' name ': ' Liu ', ' age ': 23}
Del dic[' name '] button to delete a key value pair
Print (dic)

del dic Delete entire dictionary
Print (dic)
other operations and the methods involved
Create
Dic=dict.fromkeys ([' a ', ' b ', ' C '], ' d ')
Print (dic)
Sort of dictionary
Sort by key
dic={' name ': ' Liu ', ' hobby ': ' python '}
Print (sorted (dic.items ()))
Sort by value
Print (sorted (dic.values ()))
the traversal of a dictionary
dic={' name ': ' Liu ', ' hobby ': ' python '}
For I in Dic:
Print (i,dic[i])
Two method values suggest the first type of
For i,v in Dic.items ():
Print (i,v)

Nesting of dictionaries

Av_catalog = {

"europe and America": {

"www.youporn.com": ["a lot of free, the World's largest", "general quality"],

"www.pornhub.com": ["a lot of free, also very big", "quality than Yourporn high"],

"letmedothistoyou.com": ["mostly selfie, high-quality pictures many", "resources are not many, update slow"],

"x-art.com": ["high quality, really high", "all charges, dick than please bypass"]

},

"japan and Korea": {

"tokyo-hot": ["how The quality is not clear, the individual has not liked the Japanese and Korean fan", "heard is charged"]

},

"continent": {

"1024": ["all free, really good, Good Life peace", "server in foreign countries, slow"]

}

}

Python Learning Note 3 (tuples, dictionaries)

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.