Basic Python series ---- dictionaries, basic statements, python ----

Source: Internet
Author: User

Basic Python series ---- dictionaries, basic statements, python ----

1. Definition

Ing: a data structure referenced by a name. Different from the data structure mentioned above, one is through the number of the lower mark, and the other is through the name.

A dictionary is the only built-in ing type in python. The values in the dictionary have no special order, but they are stored under a specific key. Keys can be numbers, characters, and even tuples.

A dictionary consists of key-value pairs consisting of multiple keys and their corresponding values.

 

1 phonebook = {'Tom ': '000000', 'beth': '000000'} 2 names = {}View Code

 

Dict function, which can be used to map or create a dictionary for the sequence.

Len (d) function, returns the number of key-value pairs in d.

D [k], returns the value associated with the key k

D [k] = x. Associate the value x with the key k.

Del d [k]: Delete the key k

K in d. Check whether the key k is in d.

 

 

1 items = [('name', 'gumby'), ('age', 22)] 2 print (items) 3 4 d = dict (items) 5 print (d) 6 7 print (len (d) 8 print (d ['name']) 9 10 d ['age'] = 1211 print (d) 12 print ('age' in d)View Code

 

The dictionary key can be anyImmutable.

1.1 formatted string of the dictionary

We have learned how to format strings. We can use tuples and other sequences for input parameters. Of course, the dictionary can also be implemented. As follows:

Template = '''

Through the above example, we found that we can use this feature to complete some special tasks. In addition to the added string key, the conversion specifiers are the same as before. When using the dictionary in this way, you can use any number of conversion specifiers as long as the given keys can be found in the dictionary.

1.2 Dictionary Method

1. clear method, clear all items in the dictionary

2. copy method, returns a dictionary with the same key-Value Pair

3. Use the fromkeys method to create a new dictionary with the given key. Each key corresponds to a default value of None.

4. The get method returns the corresponding value based on the key name.

5. Run the has_key method to check whether the current dictionary contains a specific key.

6. The items method returns the dictionary index items in a list. The iteritems method is roughly the same as the items method, but returns an iterator instead of a list.

7. The keys method returns the keys in the dictionary in the form of a list, while the iterkeys method returns the iterator for the key.

8. pop method, get the value corresponding to the given key, and then remove this key-value pair from the dictionary

9. The popitem method returns a random key-value pair.

10. The setdefault method is similar to the get method to obtain the value of a given key. If the current key does not exist in the dictionary, the default value is returned.

11. update method: Use one dictionary to update another.

12. The values method returns the value in the dictionary as a list. The itervalues method returns an iterator for the value.

 

1 d = {'title': 'My Home page', 'text': 'Welcome to My home Page! '} 2 print (d) 3 d. clear () 4 print (d) 5 6 d = {'title': 'My Home page', 'text': 'Welcome to My home Page! '} 7 f = d. copy () 8 print (d) 9 print (f) 10 11 print ({}. fromkeys (['name', 'age']) 12 13 print (d. get ('title') 14 15 print (d. keys ())View Code

2. Basic statements

2.1print and import

1. use commas (,) for output. print is mentioned earlier to print the results. When multiple expressions are printed, use commas (,) to separate them, whether it is a string or a string of other types that are automatically converted.

2. import: import functions from the module

1 print ('Age: ', 22) 2 3 import math4 from math import pi5 from math import *View Code

2.2 assign values to magic

  1. Sequential unpacking:Unbind the sequences of multiple values and place them in the sequence of variables. This is also called recursive unpacking.

1 x, y, z = 1, 2 print ('x: ', x,', y: ', y,', z: ', z) 3 4 x, y = y, x 5 6 print ('x: ', x,', y: ', y,', z: ', z) 7 8 values = 1, 2, 3 9 x, y, z = values10 print ('x: ', x,', y: ', y,', z: ', z)View Code

From the above we can see that the elements in the sequence of unpacking must be exactly the same as the number of variables on the left of the value assignment symbol =

  2. Chain replication:Shortcut for assigning the same value to multiple variables. Example: x = y = 1

3. incremental replication:Incremental replication is a special case of chained replication, for example, x = 1; x + = 1

2.3 statement block: The pleasure of shrinking

A statement block is a group of statements that are executed or executed multiple times when the word condition is true. Place a space before the code to indent the statement to create a statement block. Generally, we use four spaces.

2.4 condition and condition statements

Conditions, we all know that in different languages, we believe there are similar expressions. in python, we can know whether the returned true (true) according to the conditions) or false ). In python, false, None, 0, "", (), [], and {} are returned. Otherwise, true is returned.

1. if, else, And elif statements, through the connection between the three, we can make different judgments and filters on our logic.

 

1 num = input ('enter a number: ') 2 if num> 0: 3 print ('the number is positive') 4 elif num <0: 5 print ('the number is negative ') 6 else: 7 print (The number is zero ')View Code

 

2. Comparison operators:

Python comparison operator
Expression Description
X = y X equals to y
X <y X less than y
X> y X is greater than y
X <= y X less than or equal to y
X> = y X greater than or equal to y
X! = Y X is not equal to y
X is y X and y are the same object.
X is not y X and different objects
X in y X is a member of the y container.
X not in y X is not a member of the y container.

3. asserted that the program will crash sooner or later. It is better to let it crash when the error condition appears, so as to avoid immeasurable losses to the subsequent business. We usually use the assert, for example, age = 10; assert 1 <age <10;

If age does not meet the conditions, an exception is thrown and the following statement is not executed.

2.5 cycles

1. Loop, while,

1 x = 1 2 while x <= 100: 3 print (x) 4 x + = 1 5 6 words = ['eas', 'is, 'any ', 'X', 'Parrot'] 7 for word in words: 8 print (word) 9 10 for number in range (1,100): 11 print (number)View Code

2. dictionary looping

1 d = {'X': 1, 'y': 2, 'z': 3} 2 for key, value in d. items (): 3 print (key, 'corredponds to ', value)View Code

3. iterate in parallel. Generally, two lists with the same number are combined into a list of tuples through the corresponding subscript using the zip method.

Names = ['Anne ', 'beth', 'George ', 'damon'] ages = [12, 23, 34,45] for I in range (len (names )): print (names [I], 'is, ages [I], 'ears old') zips = zip (names, ages) print (zips) for name, age in zips: print (name, 'is ', age, 'ears old ')View Code

4. Flip and sort iterations. And reversed and sorted Methods

 

1 print (sorted ([2, 5, 4, 3, 1]) 2 3 print (sorted ('hello, world! ') 4 5 print ('. join (list (reversed ('hello, world! '))))View Code

 

5. jump out of the loop. There are currently two methods: continue: end the current iteration, jump to the next iteration; break, end the current entire loop, and subsequent code outside the previous loop.

2.6 list derivation ---- lightweight Loop

List derivation: a method for creating a new list using another list. The operation is similar to a for loop.

 

1 d = [x * x for x in range (10)] 2 print (d) 3 4 d = [x * x for x in range (10) if x % 3 = 0] 5 print (d) 6 7 d = [(x, y) for x in range (3) for y in range (3)] 8 print (d)View Code

 

Listing is very useful for us, especially when building some objects.

3. Write it at the end

If you have some help, please try again.Like!

If you need to reprint it, please indicate the source!

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.