Python basic data type

Posted by groberts23 on Tue, 15 Feb 2022 12:12:49 +0100


In python, there are two types of data. Built in and custom.

Built in data types include numbers, strings, Booleans, lists, tuples, dictionaries, Bytes, collections, and some less commonly used data types. Customized data types are generally in the form of classes, and the above built-in types are combined as required to become unique data types.

Data type is a very important part of Python language (which part is not important?), In particular, the native operations supported by different data types are a top priority and need to be skillfully memorized in the mind. Many times, when writing large projects, you don't need many complex skills, just use these data operation methods.

One of the reasons is to better allocate and manage memory and save unnecessary expenses. If there is no difference in data types, all objects must allocate space according to the size of the house required by the largest object, that is, memory space. This waste is too serious. With the data type, the computer can allocate the size and reasonable expenses according to the predefined space requirements of the type. The memory is saved and simplified, and the reading speed and operation efficiency can be improved.

The second reason is to facilitate unified management and provide the same API. In this way, we can provide the same operation for the same data type and restrict other impermissible behaviors. It is also easy to find errors and locate problems.

The third reason is that distinguishing data types is more appropriate to human's habit of classified management of natural things. We humans have carried out various classifications of things. Plants are plants, animals are animals, books are books and pens are pens. After classification, we naturally know that books can be read and pens can be written. The same is true of data types, which enable us to have distinguishable behavior and natural memory of abstract data.

01. Value type:

Number type

The numeric type is immutable. The so-called immutable type means that once the value of the type is different, it is a new object. The numbers 1 and 2 represent two different objects respectively. Reassigning a numeric type to a variable will create a new numeric object.

I still want to emphasize the relationship between Python variables and data types. Variables are only references to an object or codes, names, calls, etc. variables themselves have no concept of data types. Only objects such as 1, [1, 2] and "hello" have the concept of data type.

Python supports three different number types, integer, floating point, and complex.


Integer introduction

Usually called an integer, the value is positive or negative without a decimal point. The integer of python 3 can be used as the Long type, so python 3 does not have the Long type of python 2.

When representing a number, it is usually expressed in decimal

Sometimes we use octal or hexadecimal:

  • Hexadecimal is represented by 0x prefix and 0-9, a-f, for example: 0xff00
  • Octal is represented by 0o prefix and 0-7, such as 0o45
>>> hex(11)# 10 Turn 16'0xb'>>> oct(11)# 10 Turn 8'0o13'>>> bin(11)# 10 turns 2'0b1011 '


Integer memory
python has an integer length of 32 bits and usually allocates memory space continuously.

>>> id(-2)1509059968>>> id(-1)1509060000>>> id(-1)-id(-2)32

From the above spatial address, the difference between addresses is exactly 32.

Small integer object pool

When Python initializes, it will automatically establish a small integer object pool to facilitate our call and avoid repeated generation in the later stage! This is an array of 262 pointers to integer objects, ranging from - 5 to 256. In other words, for example, the integer 10, even if we did not create it in the program, has been quietly created for us in the python background.

Why? We all know that integers in this range are frequently used when programs are running, including Python's own running environment in the background. If you create one for each need, it will undoubtedly increase a lot of overhead. Creating a small integer object pool that always exists, never destroys, and takes it with you is undoubtedly a more affordable approach.


From the addresses of id(-6) and id(257), we can see that the range of small integer object pool is exactly - 5 to 256.

Integer buffer
In addition to the small integer object pool, Python also has the concept of integer buffer, that is, the integer that has just been deleted will not be deleted and recycled immediately. Instead, it will be buffered in the background for a period of time and wait for the next possible call.

a = 100000print(id(a))del ab = 100000print(id(b))30288424916003028842491600

Above, I assigned the integer 100000 to variable a and looked at its memory address. Then I delete a and create a new variable b, which is still assigned 100000. Look at the memory address of b again, which is the same as that of a before.

Note: no effect can be demonstrated in the interactive environment. This effect is realized in pycharm; And note that it is not the value in the small integer object pool.

Floating point number

Introduction to floating point numbers

Floating point numbers are decimals, such as 1.23, 3.14, - 9.01, and so on. However, for large or small floating-point numbers, it is generally expressed by scientific counting method. Replace 10 with E, 1.23x10^9 is 1.23e9, or 12.3e8, 0.000012 can be written as 1.2e-5, etc.

Conversion between floating point numbers and integers

>>> a = 1>>> float(a)# Integer to floating point 1.0>>> b = 2.2>>> int(b)# Floating point to integer 2


Introduction to plural

The complex number is composed of real part and imaginary part, which can be represented by a + bj or complex(a,b). Both real part a and imaginary part B of the complex number are floating points.

Creation of complex numbers

>>> a = 1>>> b = 2>>> complex(a,b)# a is the real part, b is the imaginary part (1+2j)

Mathematical calculation
For mathematical calculation, in addition to the simple addition, subtraction, multiplication and division mentioned above, more scientific calculation needs to be imported into math library, which contains the vast majority of scientific calculation functions we may need, as shown in the table below

ceil(x) Returns the ascending integer of a number, such as math.ceil(4.1) Return to 5 exp(x) return e of x pow (ex),as math.exp(1) Return 2.718281828459045fabs(x) Returns the absolute value of a number, such as math.fabs(-10) Return to 10.0floor(x) Returns the rounded down integer of a number, such as math.floor(4.9)Return 4 log(x) as math.log(math.e)Return 1.0,math.log(100,10)Return 2.0log10(x) Returns a value based on 10 x Logarithm of, e.g math.log10(100)Return 2.0modf(x) return x The integer part and decimal part of, the numerical symbols of the two parts and x Similarly, the integer part is represented by floating point. pow(x, y) x**y Calculated value. sqrt(x) Return number x Square root of acos(x) return x Arccosine radian value of. asin(x) return x Arcsine radian value of. atan(x) return x Arctangent radian value of. atan2(y, x) Returns the given X and Y The arctangent of the coordinate value. cos(x) return x Cosine of the radian of. hypot(x, y) Returns the Euclidean norm sqrt(xx + yy)sin(x) Returned x The sine of the radian. tan(x) return x The tangent of the arc. degrees(x) Convert radians to angles,as degrees(math.pi/2) , Return to 90.0radians(x) Convert angles to radians

Application examples:

import mathmath.ceil(4.1)  # 5 Round up math.floor(4.5) # 4 Round down math.pow(2,3)   # 8.0 the third power of 2

Common python built-in functions:

max(x1, x2,...) Returns the maximum value of a given parameter, which can be a sequence. min(x1, x2,...) Returns the minimum value of a given parameter, which can be a sequence. abs(x) Returns the absolute value of a number, such as abs(-10) Return to 10. round(x [,n]) Returns a floating point number x Rounded to the nearest couple, as given n Value represents the number of digits rounded to the decimal point.

02. Boolean type

Boolean type introduction

For error, 0 and 1, positive and negative, they are Boolean types in the traditional sense.

But in Python, Boolean types have only two values, True and False. Please note that it is the right or wrong of English words, and the first letter should be capitalized, and other fancy variants are not allowed.

Boolean values are usually used to determine whether the condition is true. For example:

a = 1if a > 3:print("a Is a number greater than 3")else:print("a Not a number greater than 3")

bool() use

Python's built-in bool() function can be used to test the boolean result of an expression.


>>> bool(1)True>>> bool(0)False>>> bool([])False>>> bool(())False>>> bool({})False>>> bool(-1)True>>> bool('')False>>> bool("False")True>>> bool("True")True>>> bool(0.0)False>>> bool(1.0)True>>> bool(-0.0)False

In a word, 0, 0.0, - 0.0, empty string, empty list, empty tuple and empty dictionary are all judged as False; While - 1 and "False" are judged to be True.

Boolean type operation

● and operation is an and operation. The result of and operation is True only if all are True:

>>> True and TrueTrue>>> True and FalseFalse>>> False and FalseFalse>>> 5 > 3 and 3 > 1True


  • The or operation is an or operation. As long as one of them is True, the result of the or operation is True:
>>> True or TrueTrue>>> True or FalseTrue>>> False or FalseFalse>>> 5 > 3 or 1 > 3True


  • not operation is a non operation. It is a monocular operator, which changes True to False and False to True:
>>> not TrueFalse>>> not FalseTrue>>> not 1 > 2True


  • When doing four operations, regard True as 1 and False as 0.
>>> True > FalseTrue>>> True < FalseFalse>>> True >=FalseTrue>>> True -10>>> True + 12>>> True *33>>> False -1-1

Null value

Null value is not boolean type. Strictly speaking, it is inappropriate to put it here, but it is closely related to Boolean.

Null value is a special value in Python, which is represented by none (initial capital). None cannot be understood as 0 because 0 is an integer type and none is a special value. None is not a boolean type, but a NoneType.

>>> bool(None)# The bool value of None is always false > > > type (None) < class' nonetype '>

03. String type

String introduction

String is one of the most commonly used data types in Python. Single or double quotation marks are used to create string, and three quotation marks are used to create multiline string.

String creation

s1 = "hello qianan"print(s1)s2 = 'hello qianan'print(s2)s3 = '''hello qianan'''print(s3)

be careful:

  • 1. Single quotation marks and double quotation marks are a pair
  • 2. All symbols are in English

Introduction to storage mode

String is an immutable sequence data type. You cannot directly modify the string itself, just like the number type!

However, are the following num and num1 stores the same?

num = 200num1 = "200"

In fact, for numeric types, the maximum value that can be stored in a byte is 256, so num is stored in one byte.

However, because the string itself is a sequence data structure, the storage mode of num1 as "200" is "2", "0" and "0" are stored in 3 bytes respectively.

Subscript string

Because the string is a sequential data structure, when we want to take a letter from "hello world", we will index it (starting from 0 by default).

>>> s1 = "hello world">>> s1[1]'e'>>> s1[10]'d'>>> s1[-1]'d'>>> s1[11]Traceback (most recent call last):  File "<stdin>", line 1, in <module>IndexError: string index out of range


Why is a string an immutable data type?  

>>> s2 = "hello world">>> s2[4] = 'l'Traceback (most recent call last):  File "<stdin>", line 1, in <module>TypeError: 'str' object does not support item assignment


String slicing

On the dos command line, enter help(slice) to view the slice description document.

Slice parameters:

  • Start start position. The default index starts from 0
  • stop end position, default to the last element
  • Step step, the default is 1


>>> help(slice)Help on class slice in module builtins:class slice(object) |  slice(stop) |  slice(start, stop[, step]) | |  Create a slice object.  This is used for extended slicing (e.g. a[0:10:2]).


Slicing practice

  • s3 = "hello world"
  • How to get the world value?
  • The code is as follows:
>>> s3 = "hello world">>> s3[6:10]# be careful,Left closed right open'worl'>>> s3[6:11]'world'>>> s3[6:]# If you do not write, you will get the last 'world' by default


  • How to get the value of hlowrd? If it is found that one is taken every other, the step size is 2
  • The code is as follows:
>>> s3[::2]'hlowrd'


  • s3 how to output in reverse order?
  • The code is as follows:
>>> s3[::-1]'dlrow olleh'


String type conversion

  • Convert string to integer type
>>> int('1')1>>> int('a')# Error reporting note: int() is decimal traceback (most recent call last): file "< stdin >", line 1, in < module > valueerror: invalid literal for int() with base 10: 'a'


  • Convert integer type to string
>>> str(1)'1'


String composition

  • +No. direct splicing
print('1'+'2')  # 12


  • %s %d %f
name = 'qianan'age = 18print('%s Age%d'%(name,age)) 


  • str.format()
name = 'qianan'age = 18print('{}Age{}'.format(name,18))print('{1}Age{0}'.format(18,name))


  • f''
name = 'qianan'age = 18print(f'{name}What is your age{age}')


Common operations of string

  • S. Find (sub) -- > returns the smallest index of the element
>>> s4 = 'hello python'>>> s4.find('e')1>>> s4.find('o')# When there are multiple elements,Return minimum index 4>>> s4.find('c')# - 1-1 if not found


  • S. Index (sub) -- > returns the smallest index of the element

In fact, the function of this method is the same as that of s.find (), but the only difference is that when the element does not exist, the s.index() method will report an error. Therefore, it is recommended to use s.find()

  • S. Replace (old, new [, count]) -- > replace
>>> s5 = "hello python">>> s5.replace('l','a')  # take'l'replace with'a',replace all'heaao python'>>> s5'hello python' # Note: the original string has not been changed>>> s5.replace('l','a',1)# If only one is replaced, specify the count parameter as 1 to 'healo python'


  • S. Split (sep = None) -- > split the string with sep and return the list. sep defaults to None, and segmentation defaults to spaces
>>> s6 = 'hello everyboby ye!'>>> s6.split(' ')['hello', 'everyboby', 'ye!']


  • S. Startswitch (prefix [, start [, end]]) -- > determines whether the string starts with a prefix and returns a bool value.
>>> s7 = "hello world">>> s7.startswith("he")True


S. Endswitch (suffix [, start [, end]]) -- > determines whether the string ends with a suffix and returns a bool value.

>>> s7'hello world'>>> s7.endswith('ld')True


  • S. Lower() -- > converts all strings to lowercase
  • S. Upper() -- > converts all strings to uppercase
  • S. Strip ([chars]) -- > the space around the string is removed by default
>>> s8 = '  hello world   '>>> s8.strip()'hello world'


  • S. Isalpha() -- > determines whether the string is all letters and returns the bool value
  • S.isdigit() -- > determines whether the string is all numbers and returns the bool value
  • S. Isalnum() -- > determines whether the string is all numbers or letters, there are no special characters, and the returned value is bool
  • S. Join (Iterable) -- > connect the elements in the sequence with the specified characters to generate a new string
li = ["Hello","world"]s = ','.join(li)print(s)

04. List type

List is one of the most basic and commonly used data structures in Python. Each element in the list is assigned a number as an index to indicate the position of the element in the list. The index of the first element is 0, the second index is 1, and so on.

Python's list is an ordered and repeatable collection of elements, which can be nested, iterated, modified, sliced, added, deleted and judged by members.

From the perspective of data structure, Python's list is a variable length sequential storage structure, and each location stores pointers to objects.

For this list, alist = [1, "a", [11,22], {"k1":"v1"}], its storage method in memory is as follows:



Creation method

To create a list, simply enclose the different data items separated by commas in square brackets

>>> li = []# Define an empty list. Note that the name cannot be list>>> li[]>>> li1 = [1,'qianan',3.14]# Any data type can be stored>>> li1[1, 'qianan', 3.14]>>> li2 = list()>>> li2[]>>> li3 = list('hello')# list(iterable)>>> li3['h', 'e', 'l', 'l', 'o']


Access elements in the list

The list starts from 0 and creates a subscript index for each of its elements in order until the total length is reduced by one. To access one of its elements, use square brackets and subscript values. Pay attention to ensure that the index does not exceed the range. Once the accessed index exceeds the range, an exception will be thrown. So, be sure to remember that the index of the last element is len(list)-1.

>>> lis = ["a", "b", "c"]>>> lis[0]'a'>>> lis[1]'b'>>> lis[2]'c'>>> lis[3]Traceback (most recent call last):  File "<pyshell#7>", line 1, in <module>    lis[3]IndexError: list index out of range


Modify the value of the element

Reassign the element directly.

>>> li1 = [1,2,3]>>> li1[1]2>>> li1[1] = 5>>> li1[1, 5, 3]>>> li1[1:] = [6,7]>>> li1[1, 6, 7]


Delete element

Use del statement or remove(), pop() method to delete the specified element.

>>> lis = ["a", "b", "c"]>>> del lis[0]      # Delete by index>>> lis['b', 'c']>>> lis.remove("b") # Delete directly by value>>> lis['c']>>> lis.pop()       # Pop up last'c'>>> lis[]l1 = [1, 'hello', 1]l2 = l1.pop(1)  # Pop up 1 as index print(l2) according to the index


Special operations for lists

# Statement result description[1, 2, 3] + [4, 5, 6]    # [1, 2, 3, 4, 5, 6] Combine two lists l1 = [1, 2, 3]l2 = [4, 5, 6]print(l1.__add__(l2))     # The underlying call__add__method['Hi!'] * 4       # ['Hi!', 'Hi!', 'Hi!', 'Hi!']      Multiplication of lists l1 = [1, 2, 3]print(l1.__mul__(3))3 in [1, 2, 3]    # True determines whether the element exists in the list. L1 = [1, 2, 3] print (L1. _contains__ (1))


List of common functions

# Function function>>> l1 = [1, 2, 3]>>> len(l1) # Returns the number of list elements, that is, the length of the list l1.__len__()3>>> max(l1) # Returns the maximum value of a list element  max(l1)  max(1,2,3,4)3>>> min(l1) # Returns the minimum value of list element 1>>> list('hello') # Convert list to sequence['h', 'e', 'l', 'l', 'o']>>> s = list((1, "a", "b", 2))>>> s[1, 'a', 'b', 2]>>> max(s)          # Cannot mix different types for max min evaluation Traceback (most recent call last):  File "<pyshell#20>", line 1, in <module>    max(s)TypeError: '>' not supported between instances of 'str' and 'int'


Sorting and inversion

>>> li = [1,2,3,4,5,2,1,3,1]>>> li.reverse()# Invert the list to modify itself *IN PLACE*>>> li[1, 3, 1, 2, 5, 4, 3, 2, 1]>>> li.sort()# Sort, default ascending L.sort(key=None, reverse=False)>>> li[1, 1, 1, 2, 2, 3, 3, 4, 5]>>> li.sort(reverse=True)# reverse=True descending > > > Li [5, 4, 3, 3, 2, 2, 1, 1, 1]


Slice (cut)

Slicing refers to intercepting a sequence and selecting a segment in the sequence.

The syntax of slicing is: list[start:end:step]

Divide the index with a colon, start represents the starting point index, end represents the ending point index, step is the step size, and the default is 1. Omitting start means to start with 0, and omitting end means to the end of the list. Note that the interval is closed on the left and open on the right!

If a negative integer subscript is provided, search from the end of the list to the head. For example, - 1 represents the last element and - 3 represents the penultimate element.

In the slicing process, you can also set the step size, which is divided by the second colon, such as list[3:9:2], indicating the distance between each element.

>>> l3 = ['a','b','c','d','e','f']>>> l3[1]# take'b'be careful: index Default start from 0'b'>>> l3[2]# take'c''c'>>> l3[1:3]# take['b', 'c']Note: left closed right open['b', 'c']>>> l3[:3]# take['a', 'b', 'c']be careful: start Do not write default start from scratch['a', 'b', 'c']>>> l3[2:]# take['c', 'd', 'e', 'f']be careful: end Don't write default to last['c', 'd', 'e', 'f']>>> l3[:]# Take all['a', 'b', 'c', 'd', 'e', 'f']>>> l3[::2]# take['a', 'c', 'e']Note: the step size is 2['a', 'c', 'e']>>> l3[::-1]# Reverse order ['f ',' e ','d', 'C', 'B', 'a']


Multidimensional list (nested list)

>>> a = [[1,2,3],[4,5,6],[7,8,9]]>>> a[0][1]2


Traversal of list

There are several ways to traverse the list:

a = [1,2,3,4,5,6]for i in a:             # Traverse each element itself    print(i)for i in range(len(a)):     # Traverse the subscript of the list and take value through the subscript    print(i, a[i])x = 9if x in a:       # Judge whether it belongs to a list member. The operation speed is very fast. print("True")else:    print("False")


Built in methods for lists

  • append(obj) adds a new object to the end of the list
  • count(obj) counts the number of times an element appears in the list
  • extend(seq) append multiple values in another sequence at the end of the list at one time (expand the original list with the new list)
  • index(obj) finds the index position of the first match of a value from the list
  • insert(index, obj) inserts objects into the list
  • pop(obj=list[-1]) removes an element in the list (the last element by default) and returns the value of the element
  • remove(obj) removes the first match of a value in the list
  • Reverse element in reverse list
  • sort([func]) sorts the original list
  • copy() copy list
  • clear() clears the list, which is equal to del lis [:]
>>> li = [1,2,3]>>> li.append([3,3])>>> li[1, 2, 3, [3, 3]]>>> li = [1,2,3,[3,3]]>>> li.count(3) 1>>> li = [1,2,3]>>> li.extend([4,5])   >>> li[1, 2, 3, 4, 5]>>> li = [1,2,3,2,3]>>> li.index(3) 2>>> li = ['happy','year']>>> li.insert(1,'new')>>> li['happy', 'new', 'year']>>> li = [1,2,3]>>> li.clear() >>> li[]

Note: methods such as append, insert and remove modify the list itself and do not return a value (strictly speaking, return None).  

05. Tuple type

Tuple introduction

Enclosed in parentheses are tuples.

Tuple is also a sequence structure, but it is an immutable sequence. You can simply understand it as a list with immutable content. Tuples are used in much the same way as lists, except that the internal elements cannot be modified.

Tuple creation

>>> tu = ()>>> tu()>>> tu1 = tuple()>>> tu1()>>> type(tu)<class 'tuple'>>>> type(tu1)<class 'tuple'>

Tuples are the same as lists
Use square brackets and subscripts to access elements

>>> tu = (1,2,3,4,5)>>> tu[1]2

Slice (form new metagroup object)

>>> tu(1, 2, 3, 4, 5)>>> tu[2:4](3, 4)


>>> tu1 = (1,2,3,4,5,5,5,4)>>> tu1.count(5)3>>> tu1.index(5)4

There is also a list Reverse() and list Sort(), but tuples are not, but to realize inversion and sorting, you can use the built-in function in python: reversed(), sorted()

>>> tu1(1, 2, 3, 4, 5, 5, 5, 4)>>> reversed(tu1)<reversed object at 0x000001B9FE543C88>>>> tuple(reversed(tu1))(4, 5, 5, 5, 4, 3, 2, 1)>>> tu = (1,2,3,5,4,3)>>> sorted(tu)# Ascending [1, 2, 3, 3, 4, 5]




Operation not allowed in tuple

It is not allowed to modify or add elements

>>> tup = (1,2,3)>>> tup[2] = 5Traceback (most recent call last):  File "<stdin>", line 1, in <module>TypeError: 'tuple' object does not support item assignment

Once you want to change the tuple, you can only reopen a piece of memory and create a new tuple

>>> tup = (1,2,3)>>> new_tup = tup+(4,)>>> new_tup(1, 2, 3, 4)

Note: a tuple only guarantees that its first level child elements are immutable. For nested elements, immutability is not guaranteed

As follows:

>>> tup = (1,2,3,['qianan',5])# take'qianan'Change to 4>>> tup[3][0] = 4>>> tup(1, 2, 3, [4, 5])>>> tup1 = (1,2,3,('qianan',5))# Change 'qianan' to 4 > > > Tup1 [3] [0] = 4trackback (most recent call last): file "< stdin >", line 1, in < module > typeerror: 'tuple' object does not support item assignment

Deleting an element is not allowed (but the whole tuple can be deleted)
In fact, all methods that modify elements inside tuples. For example, tuples have no remove, append, pop and other methods

Conversion of lists and tuples
Tuple to list

>>> tu = (1,2,3)>>> list(tu)[1, 2, 3]

Convert list to tuple

>>> li = [1,2,3]>>> tuple(li)(1, 2, 3)

06. Dictionary type


Dictionary introduction
Python's dictionary data type is implemented based on hash algorithm. It adopts the form of key value pair (key:value), and calculates the address of value according to the value of key. It has very fast retrieval and insertion speed. However, it is out of order, contains unlimited number of elements, and the type of value can also be any other data type!

The key of the dictionary must be immutable objects, such as integers, strings, bytes and tuples, but the most used is strings. Lists, dictionaries, collections, etc. cannot be used as keys. At the same time, the key in the same dictionary must be unique, but the value is not necessary.

In short, dictionaries can be accurately described as collection types with variable length, disorder and hash

Each key value pair of the dictionary is separated by colon (:), and each pair is separated by comma (,), and the whole dictionary is included in curly brackets ({}).
For example:

d = {key1 : value1, key2 : value2 }


Create dictionary

Create an empty dictionary

>>> dic = {}>>> dic{}>>> type(dic)<class 'dict'>>>> dict(){}

There are three ways to create a dictionary

>>> dic1 = {'name':'qianan','age':'18'}>>> type(dic1)<class 'dict'>>>> dic2 = dict(name="qianan",age='18')>>> type(dic2)<class 'dict'>>>> dic3 = dict([('name','qianan'),('age','18')])>>> type(dic3)<class 'dict'>>>> dic1 == dic2 == dic3# ==Compare values True


ACCESS Dictionary

Dictionary is a collection type, not a sequence type, so there is no concept of index subscript, let alone slicing. However, similar to list, the dictionary takes the value by putting the corresponding key in square brackets to obtain the corresponding value.

>>> dic1 = {'name':'qianan','age':18}>>> dic1['name']'qianan'>>> dic1['gender']# When the key value does not exist, an error is reported: traceback (most recent call last): file "< stdin >", line 1, in < module > keyerror: 'gender'


Additions and modifications

Adding is to insert a new key value pair into the dictionary, and modifying is to give a new value to the original key. Since a key can only correspond to one value, if a key is assigned multiple times, the subsequent value will flush out the previous value.

>>> dic1 = {'name':'qianan','age':18}>>> dic1['gender'] = "female"# increase key Value is"gender",value Value is"female"Element of>>> dic1{'name': 'qianan', 'age': 18, 'gender': 'female'}>>> dic1['gender'] = 'male'# When there is the key:value value value, take it out and re assign it, and modify it > > > dic1{'name':'qianan ',' age ': 18,' gender ':'male'}


Delete dictionary element, empty dictionary and delete dictionary

Use the del keyword to delete dictionary elements or the dictionary itself, and use the clear() method of the dictionary to empty the dictionary

>>> dic1{'name': 'qianan', 'age': 18, 'gender': 'male'}>>> del dic1['name']# Delete a key:value element>>> dic1{'age': 18, 'gender': 'male'}>>> dic1{'age': 18, 'gender': 'male'}>>> dic1.clear()# Empty dictionary>>> dic1{}>>> del dic1# Delete the entire dictionary > > > dic1traceback (most recent call last): file "< stdin >", line 1, in < module > NameError: name 'dic1' is not defined


Dictionary method

  • get(key) returns the value of the specified key. If the value is not in the dictionary, it returns the default value
  • items() returns a list of traversable (key, value) tuple pairs
  • keys() returns all the keys of the dictionary in a list
  • values() returns all the values of the dictionary in a list

The code is as follows:

>>> dic1 = {'name':'qianan','age':18}>>> dic1.get('name')'qianan'>>> dic1.get('gender')# When key:value does not exist, return none > > > dic1 items()dict_ items([('name', 'qianan'), ('age', 18)])>>> for k,v in dic1. items():...      print(k,v)... name amyage 18>>> dic1. keys()dict_ keys(['name', 'age'])>>> dic1. values()dict_ values(['qianan', 18])

07. bytes type

bytes introduction

After Python 3, string and byte types are completely separated. Strings are processed in character units, and bytes types are processed in bytes.

The byte data type is basically the same as the string data type in all operations and use, and even built-in methods. It is also an immutable sequence object.

In Python 3, bytes is usually used for network data transmission, binary image and file storage, etc.

bytes creation

You can generate bytes instances by calling bytes(), whose value form is b'xxxxx '. For the same string, if you generate bytes objects with different encoding methods, different values will be formed.

>>> a = b'hello'>>> type(a)<class 'bytes'>>>> b = bytes('hello',encoding='utf8')>>> type(b)<class 'bytes'>

Common conversion of bytes type

In practical application, we usually convert bytes type to str type.

  • Byte to string
>>> d = b'world'>>> d.decode()'world'>>> type(d)<class 'bytes'>


  • String to byte
>>> e = 'world'>>> e.encode()b'world'>>> type(e)<class 'str'>

08. Set set type

Collection introduction

Set is a basic set of test elements, which does not include the duplicate relationship between set and unordered elements.

The core of collection data type is automatic de duplication.

Create collection

Collections use curly braces ({}) to frame elements, separated by commas. But note: if you want to create an empty set, you must use set() instead of {}, because the latter creates an empty dictionary.

>>> s = {1,2,3}>>> s{1, 2, 3}>>> type(s)<class 'set'>>>> s = {}# Note that empty {} will default to dictionary > > > type (s) < class' dict '>


Collections can also be created using the set() function.

The usage is as follows:

  • Set() - > new empty set object
>>> s = set()# Create an empty set > > > set() > > > type (s) < class' set '>


  • Set (Iterable) - > new set object
>>> s = set([1,2,3,1,2,3,4])# Create a collection and remove duplicates>>> s{1, 2, 3, 4}>>> s1 = set("hello world")# Create a collection and remove duplicates>>> s1{'h', 'd', 'o', ' ', 'e', 'l', 'r', 'w'}>>> s2 = set(123)# Note that an iteratable object needs to be passed in, but 123 of type int is not, so the error traceback (most recent call last): file "< stdin >", line 1, in < module > typeerror: 'Int' object is not iteratable


Add element to collection

Elements can be added to the set through the add(key) method. They can be added repeatedly, but there will be no effect:

>>> s = set([1,2,3,1,2,3,4])>>> s{1, 2, 3, 4}>>> s.add(3)# Repeat add,Automatic weight removal>>> s{1, 2, 3, 4}>>> s.add(6)# Added successfully>>> s{1, 2, 3, 4, 6}>>> s.add("qianan")# Added successfully>>> s{1, 2, 3, 4, 6, 'qianan'}>>> s.add([1,2,3])# An error is reported. Like a dictionary, a variable object traceback (most recent call last): file "< stdin >", line 1, in < module > typeerror: unharable type: 'list' cannot be added


Collection Update
You can use the update() method to update another object to the existing collection. This process will also be de duplicated.

>>> s = set([1,2,3,4,5])>>> s.update("hello")# take hello Unpack and put into collection>>> s{1, 2, 3, 4, 5, 'h', 'o', 'e', 'l'}>>> s.update("hello")# Still weight removal > > > s{1, 2, 3, 4, 5, 'H', 'o', 'e', 'l'}

Delete element

Delete the specified element through the remove(key) method, or use the pop() method. Note that the pop method of the collection cannot set parameters and delete the specified element:

  • set.remove()
>>> s = {1, 2, 3, 4, 5, 'h', 'o', 'e', 'l'}>>> s.remove(1)# Delete this element>>> s{2, 3, 4, 5, 'h', 'o', 'e', 'l'}>>> s.remove('h')# Delete this element>>> s{2, 3, 4, 5, 'o', 'e', 'l'}>>> s.remove('www')# When deleting a non-existent element, an error is reported: traceback (most recent call last): file "< stdin >", line 1, in < module > keyerror: 'www'
  • set.pop()
>>> s1 = set("hello world")>>> s1.pop()'h'>>> s1.pop()'d'>>> s1.pop()# Note: random deletion'o'>>> s1.pop(1)# Cannot delete through the index because it is out of order. Traceback (most recent call last): file "< stdin >", line 1, in < module > typeerror: pop() takes no arguments (1 given)

It should be noted that the collection cannot take out an element, because the collection does not support subscript index or dictionary retrieval through key value pairs.

>>> s1{' ', 'e', 'l', 'r', 'w'}>>> s1[1]Traceback (most recent call last):  File "<stdin>", line 1, in <module>TypeError: 'set' object does not support indexing

The collection data type belongs to Python's built-in data type, but it is not paid attention to, and there is even no introduction in many books. In fact, set is a very useful data structure. Its de duplication and set operation are functions that other built-in types do not have. It plays a very important role in many occasions, such as web crawler.  


Topics: Python Back-end