The 13th day of Python learning

Posted by misty on Sat, 01 Jan 2022 16:51:39 +0100

The 13th day of Python learning

Today is the end of the second week of Python learning. I will sort out the knowledge points learned this week as usual

random

import random
# random. The range function can randomly select data from a range
num1 = random.randrange(1,11)
print(num1)	# 6

names = [1, 3, 5, 7, 8, 10, 9, 6]
# The len function returns the number of elements in the list
print(len(names))	# 8
# The sample function can sample list elements without putting them back
print(random.sample(names, k=5))	# [8, 3, 6, 10, 1]
# The choices function can sample the list elements back (it can be sampled repeatedly). When used, k = n must be used to represent the number of samples, and the output is a list
print(random.choices(names, k=5))	# [8, 7, 10, 9, 8]
# The choice function can randomly select an element from the list
print(random.choice(names))	# 8
# The shuffle function can realize the random disorder of list elements and return a new list
random.shuffle(names)
print(names)	# [10, 5, 6, 8, 9, 7, 3, 1]

list

Preliminary understanding of the list

  1. A list is a container data type
  2. A list is a data sequence composed of a series of elements in a specific order. It can save multiple data and allow the construction of repeated data lists
  3. A list is a variable data type
  4. Nested list: the elements in the list can be lists, which are suitable for storing data in tabular form

Construction of lists

# Way to create a list: literal syntax
list1 = ['apple', 'orange', 'pitaya', 'durian'] 
print(list1)	# ['apple','orange','pitaya','durian']

# The second way to create a list: constructor syntax
list2 = list(range(1, 10)) 
print(list2)	# [1,2,3,4,5,6,7,8,9]

# The third way to create a list: generative (deductive) syntax
list3 = [i ** 2 for i in range(1, 10)]
print(list3)	# [1,4,9,16,25,36,49,64,81]

List related operations

# List repetition
list4 = [1, 10, 100] * 5
print(list4)	# [1, 10, 100, 1, 10, 100, 1, 10, 100, 1, 10, 100, 1, 10, 100]

# Member operation of list
print(10 in list4)	# True
print(5 not in list4)	# True

# Splicing of lists
list5 = [1, 3, 5, 7]
list6 = [4, 4, 8]

# Traverse the elements in the list
for i in range(len(list5)):
    print(list1[i])	# 1	 3	5  7
for x in list5:
    print(x)	# # 1  3  5  7
    
# List enumeration, which can output elements and their corresponding sequence numbers at the same time
for i, x in enumerate(list5):
    print(i, x)	#0 1	1 3 	2 5		3 7
    
# Method 1: splice by +
list6 = list5 + list6
list6 += list5

# Method 2: splice through the function extend()
list6.extend(list5)
print(list6)	# [1, 3, 5, 7, 4, 4, 8, 1, 3, 5, 7, 1, 3, 5, 7]


# Index of the list
# Indexes include positive indexes (from 0 to length - 1) and negative indexes (from - 1 to - length)
print(list5[0], list[-1])	# 1 7

# Reassign by index operation
list5[-1] = 100
print(list5[len(list5)-1], list5[-1])	# 100 100

# Slice of list
import random

nums = [random.randrange(1, 100) for _ in range(9)]
print(nums)	# [13, 7, 32, 92, 16, 72, 74, 85, 34]

# The default step size is 1
print(nums[2:])	# [32, 92, 16, 72, 74, 85, 34]

# The default is from 0 to the list length
print(nums[::])	# [13, 7, 32, 92, 16, 72, 74, 85, 34]

# Reversal of list
print(nums[::-1])	# [34, 85, 74, 72, 16, 92, 32, 7, 13]
print(nums[1:3])	#[7, 32]

# The step size of the list is 2
print(nums[2:7:2])	# [32, 16, 74]

# Only the part not exceeded can be obtained
print(nums[10:15])	# []
print(nums[6:10]	# [74, 85, 34]

# When the step size is positive, the start boundary shall be greater than the end boundary
print(nums[5:1])	#[]

# Comparison -- > less used in actual work (negligible)
# Compare elements corresponding to subscripts between lists
# List and value each element is compared with the value
# Just compare the first one
# Strings can be compared, and the size is in alphabetical order
list7 = list(range(1, 8, 2))
list8 = [0, 3, 5, 7, 9]

# Compare whether the elements of two lists have the same meaning
print(list5 == list7)	# True
print(list7 != list8)	# True

# Compare the size of the corresponding elements of the two lists
print(list7 < list8)	#False

Operation method of list

# copy() copies a list, which is equivalent to a complete slice
# Index() finds the index (subscript) of the corresponding element in the list. It will not be displayed if it exceeds the range
items = ['banana', 'grape', 'apple', 'waxberry', 'pitaya', 'apple'] 

# Index() --- > find the index (subscript) of the element in the list
if 'strawberry' in items:
    print(items.index('strawberry'))
if 'apple' in items:
    print(items.index('apple'))
if 'apple' in items[3:]:
    print(items.index('apple', 3))

# Add element
# append() appends an element at the end
items.append('blueberry')

# insert() inserts an element at the specified location
items.insert(1, 'watermelon')
print(items)

items = ['banana', 'grape', 'apple', 'waxberry', 'pitaya', 'apple']

# Delete element
# pop() deletes the element corresponding to the subscript position. The last bit is deleted by default, and the deleted element can be returned
items.pop()
print(items.pop(4))

# del deletes the reference of an object, which is similar to pop, but cannot return the deleted element
del items[0]

# Delete the specified element from the list through remove(), and delete the first one from left to right. You can delete all elements through a loop
while 'apple' in items:
    items.remove('apple')
print(items)
items = ['banana', 'grape', 'apple', 'waxberry', 'pitaya', 'apple']
    
# Count() --- > counts the number of occurrences of elements in the list
print(items.count('apple'))
print(items.count('strawberry'))

# clear() please empty the list
items = ['banana', 'grape', 'apple', 'waxberry', 'pitaya', 'apple']
print(items.clear())

# reverse() reverses the list and directly modifies the original list
items = ['banana', 'grape', 'apple', 'waxberry', 'pitaya', 'apple']
print(items.reverse())

# sort() sorts the list. The string will be sorted by alphabet. By default, it is sorted from small to large (ascending), that is, reverse=False
# String type numbers are sorted by characters according to the first single number
items = ['banana', 'grape', 'apple', 'waxberry', 'pitaya', 'apple']
items.sort()
print(items)

# When reverse=True, it is sorted from large to small (in descending order).
items.sort(reverse = True)
print(items)	# ['waxberry', 'pitaya', 'grape', 'banana', 'apple', 'apple']

# Select the sorting method (for example, sorting by string or integer type) through the key in sort (). The type of the sorted element remains unchanged
nums = ['1', '10', '234', '2', '35', '100']
nums.sort(key=int)	# ['apple', 'apple', 'banana', 'grape', 'pitaya', 'waxberry']
print(nums)	# ['1', '2', '10', '35', '100', '234']

tuple

A preliminary understanding of tuples

  1. Tuple is an immutable type, which means that once a variable of tuple type is defined, the elements in it cannot be added or deleted, and the value of the element cannot be modified.
  2. There are several elements in (), which we call tuples
  3. () represents an empty tuple
  4. If there is only one element in a tuple, you need to add a comma, otherwise it is not a tuple
  5. Immutable types are more suitable for multi-threaded environments
  6. Immutable types are superior to the corresponding variable types in terms of creation time and occupied space

Construction of tuples

# Define a triplet
t1 = (30, 10, 55)
print(t1)	#(30,10,55)

# Define a quad
t2 = ('Hebei', 40, True, 'hobby')
print(t2)	# ('Hebei', '40','True', 'hobbies')

Correlation operation of tuples

# View the type of variable
print(type(t1), type(t2))    # <class 'tuple'> <class 'tuple'>

# View the number of elements in the tuple
print(len(t1), len(t2))      # 3 4

# Get the elements in the tuple through index operation
print(t1[0], t1[-3])         # 30 30
print(t2[3], t2[-1])         # Interests and hobbies

# Loop through elements in tuples
for member in t2:
    print(member)

# Member operation
print(100 in t1)    # False
print(40 in t2)     # True

# Splicing
t3 = t1 + t2
print(t3)           # (30, 10, 55, 'Hebei', 40, True, 'hobbies')

# section
print(t3[::3])      # (30, 'Hebei', 'hobbies')

# Comparison operation
print(t1 == t3)    # False
print(t1 >= t3)    # False
print(t1 < (30, 11, 55))    # True

Application scenario of tuple

  1. Packaging and unpacking operations
  2. Exchange the values of two variables
  3. Let the function return multiple values

character string

Preliminary understanding of string

  1. A finite sequence of zero or more characters
  2. Single quotation marks' 'or double quotation marks'' can be used to construct strings. Strings starting with three double quotation marks or single quotation marks can be folded. Python also allows characters to be represented by an octal or hexadecimal number after \
  3. \Representative escape
  4. The r before the string represents the original string, which means that all symbols of the string are their original meaning without escape characters

String correlation operation

# String splicing
s1 = 'hello' + ' ' + 'world'
print(s1)    # hello world

# Repetition of string

s2 = '!' * 3
print(s2)    # !!!

s1 += s2     # s1 = s1 + s2
print(s1)    # hello world!!!
s1 *= 2      # s1 = s1 * 2
print(s1)    # hello world!!!hello world!!!

# Member operation of string

s1 = 'hello, world'
print('wo' in s1)    # True
s2 = 'goodbye'
print(s2 in s1)      # False

# Index operation of string

s = 'abc123456'
N = len(s)

# Get first character
print(s[0], s[-N])    # a a

# Gets the last character
print(s[N-1], s[-1])  # 6 6

# Gets the character with index 2 or - 7
print(s[2], s[-7])    # c c

# Gets characters with indexes 5 and - 4
print(s[5], s[-4])    # 3 3

# Slicing of strings

s = 'abc123456'

# Forward slice operation with i=2, j=5, k=1 (default)
print(s[2:5])       # c12

# Equivalent to traversal of string
print(s[:])         # abc123456

# Flipping of strings
print(s[::-1])      # 654321cba

# Traversal of string
# Traversal by subscript
s1 = 'hello'
for index in range(len(s1)):
    print(s1[index])
    
# Direct traversal
s1 = 'hello'
for ch in s1:
    print(ch)
    
# String comparison
s1 = 'a whole new world'
s2 = 'hello world'
print(s1 == s2, s1 < s2)      # False True

# In Python, case represents different characters
print(s2 == 'hello world')    # True
print(s2 == 'Hello world')    # False
print(s2 != 'Hello world')    # True

# Compare according to the encoding size of characters (it is not clear that the corresponding encoding can be obtained through ord())
s3 = 'Hello'
prit(ord('you'), ord('good'))               # 20320 22909
s4 = 'Bye'
print(ord('again'), ord('see'), ord('bar'))    # 20877 35265 21543
print(s3 > s4, s3 <= s4)      # False  True

s1 = 'hello world'
s2 = 'hello world'
s3 = s2

# Compare the contents of the string
print(s1 == s2, s2 == s3)    # True True

# Compare the memory address of the string
print(s1 is s2, s2 is s3)    # False True

String related operations

# Case conversion of string

s1 = 'hello, world!'

# Use the capitalize method to get the string after the first letter of the string is capitalized
print(s1.capitalize())   # Hello, world!

# Use the title Method to get the string after the first letter of each word is capitalized
print(s1.title())        # Hello, World!

# Use the uppercase method to get the uppercase string
print(s1.upper())        # HELLO, WORLD!

s2 = 'GOODBYE'

# Use the lower method to get the lowercase string of the string
print(s2.lower())        # goodbye

# String lookup

s = 'hello, world!'

# The find method finds the location of another string from the string
# The index of the first character of another string in the return string was found
print(s.find('or'))        # 8

# Return - 1 not found
print(s.find('shit'))      # -1

# The index method is similar to the find method
# The index of the first character of another string in the return string was found
print(s.index('or'))       # 8

# Throw exception not found
print(s.index('shit'))     # ValueError: substring not found

s = 'hello good world!'

# Find the position where the character o appears from front to back (equivalent to the first occurrence)
print(s.find('o'))       # 4

# Find the position where the character o appears from the position with index 5
print(s.find('o', 5))    # 7

# Find the position where the character o appears from back to front (equivalent to the last occurrence)
print(s.rfind('o'))      # 12

# String property judgment

s1 = 'hello, world!'

# The startwith method checks whether the string starts with the specified string and returns a Boolean value
print(s1.startswith('He'))  # True
# Falseprint(s1.startswith('hel'))   # True

# The endswitch method checks whether the string ends with the specified string and returns a Boolean value
print(s1.endswith('!'))     # True

s2 = 'abc123456'

# The isdigit method checks whether a string is composed of numbers and returns a Boolean value
print(s2.isdigit())    # False

# The isalpha method checks whether a string is composed of letters and returns a Boolean value
print(s2.isalpha())    # False

# The isalnum method checks whether a string is composed of numbers and letters and returns a Boolean value
print(s2.isalnum())    # True

# Formatted output of string
s = 'hello, world'

# The center method centers the string with a width of 20 and fills it on both sides*
print(s.center(20, '*'))  # ****hello, world****

# The rjust method aligns the string to the right with a width of 20 and fills in spaces on the left
print(s.rjust(20))        #         hello, world

# The ljust method aligns the string to the left with a width of 20 and fills it on the right~
print(s.ljust(20, '~'))   # hello, world~~~~~~~~

# Split string

content = 'You go your way, I will go mine.'
content2 = content.replace(',', '').replace('.', '')

# Split the string with spaces to get a list

words = content2.split()
print(words, len(words))	# ['You', 'go', 'your', 'way', 'I', 'will', 'go', 'mine'] 8

for word in words:
    print(word)	# You  go  your  way  I  will  go  mine

# Split the string with a space. You can split it up to 3 times
words = content2.split(' ', maxsplit=3)
print(words, len(words))	# ['You', 'go', 'your', 'way I will go mine'] 4

# Split the string from right to left. It is allowed to split 3 times for long
words = content2.rsplit(' ', maxsplit=3)
print(words, len(words))	# ['You go your way I', 'will', 'go', 'mine'] 4

# Split strings with commas
items = content.split(',')
for item in items:
    print(item)	# You go your way  I will go mine.

Variable valueplaceholder Format resultsexplain
3.1415926{:.2f}'3.14'Keep two decimal places
3.1415926{:+.2f}'+3.14'Two decimal places are reserved after the signed decimal point
-1{:+.2f}'-1.00'Two decimal places are reserved after the signed decimal point
3.1415926{:.0f}'3'Without decimals
123{:0>10d}0000000123Fill 0 on the left and fill up 10 places
123{:x<10d}123xxxxxxxFill x on the right and fill up 10 places
123{:>10d}' 123'Fill in the space on the left, enough for 10 digits
123{:<10d}'123 'Fill in the space on the right, enough for 10 digits
123456789{:,}'123,456,789'Comma separated format
0.123{:.2%}'12.30%'Percentage format
123456789{:.2e}'1.23e+08'Scientific counting format

aggregate

Preliminary understanding of set

Hash
1. If an object cannot calculate the hash code, it cannot be put into the collection, and variable containers (list, collection, dictionary) cannot be put into the collection
2. The bottom layer of the set uses an efficient storage method: hash storage (hash storage). Therefore, the time efficiency of the set in element search is much higher than that of the list, which does not depend on the scale of the problem. It is a storage scheme with constant time complexity
3. List is not a hashable type
4. The storage mode of list tuple string is sequential storage. The advantage is that it can realize random access. The disadvantage is that it needs to judge whether the element exists, and the efficiency of searching the element is very low
5. Hash conflicts reduce efficiency
6. Baidu network disk speed second transmission principle: if there is no real upload, its server already has the file. Calculate the hash code locally. After uploading the hash code, after comparison, return the data: the user already has the file and changes the file name
Properties of sets
1. Dissimilarity, no duplicate elements in the set
2. Disorder. The order of elements in the set is determined by the hash code. The status of each element is the same, and the elements are disordered. Therefore, index operation cannot be supported
3. Certainty, an element, only belongs to and does not belong to the set, and there is no other ambiguity
4. The type of the collection is set
5. Empty set is set()
# The input strings are arranged randomly and duplicate elements are deleted
set5 = set('hello')
print(set5)	# {'l', 'o', 'h', 'e'}

# bool values also satisfy the set heterogeneity
set2 = {True, False, True, True, False}
print(set2)	# {False, True}

# Collections can store tuples
set3 = {(1, 2, 3), (4, 5, 6)}
print(set3)	{(1, 2, 3), (4, 5, 6)}

# Lists can store collections
list4 = [set5, set2]
print(list4)	# [{'hello'}, {False, True}]

Construction of collection

#Literal syntax for creating a collection (duplicate elements do not appear in the collection)
set1 = {1, 2, 3, 3, 3, 2}
print(set1)         # {1, 2, 3}
print(len(set1))    # 3

# Constructor syntax for creating collections (we'll talk about what constructors are later)
set2 = set('hello')
print(set2)         # {'h', 'l', 'o', 'e'}

# Convert a list into a collection (you can remove duplicate elements from the list)
set3 = set([1, 2, 3, 3, 2, 1])
print(set3)         # {1, 2, 3}

# Generative syntax for creating a collection (replace [] of list generative with {})
set4 = {num for num in range(1, 20) if num % 3 == 0 or num % 5 == 0}
print(set4)         # {3, 5, 6, 9, 10, 12, 15, 18}

Correlation operation of sets

# Loop traversal of collection elements
set4 = {num for num in range(1, 20) if num % 3 == 0 or num % 5 == 0}
for elem in set4:
	print(elem)	# 3  5  6  9  10  12  15  18

# Member set of operations
set1 = {1, 2, 3, 4, 5}
set2 = {2, 4, 6, 8}
print(1 in set1)	# True
print(1 not in set1)	# False

# Intersection union difference operation of sets
set1 = {1, 2, 3, 4, 5}
set2 = {2, 4, 6, 8}

# intersection
# Symbolic method
print(set1 & set2)	# {2, 4}

# Built in function method
print(set1.intersection(set2))	# {2, 4}

# Union
# Symbolic method
print(set1 | set2)	# {1, 2, 3, 4, 5, 6, 8}

# Built in function method
print(set1.union(set2))	# {1, 2, 3, 4, 5, 6, 8}

# Difference set
# The difference set does not satisfy the commutative law
# Symbolic method
print(set1 - set2)	# {1, 3, 5}

# Built in function method
print(set1.difference(set2))	# {1, 3, 5}

# Symbolic method
print(set2 - set1)	# {8, 6}

# Built in function method
print(set2.difference(set1))	# {8, 6}

# Symmetry difference
# Symmetric difference satisfies commutative law
# Symbolic method
print(set1 ^ set2)	# {1, 3, 5, 6, 8}

# Definition method
print((set1 | set2) - (set1 & set2))	# {1, 3, 5, 6, 8}

# Built in function method
print(set1.symmetric_difference(set2))	# {1, 3, 5, 6, 8}

set3 = {1, 2, 3, 4, 5, 6, 7, 8, 9}

# Judge true subset
# Symbolic method
print(set1 < set3)	# True

# Built in function method
print(set1.issubset(set3))	# True

# Judgment subset
print(set1 <= set3)	# True

# Judgment superset
# Symbolic method
print(set3 > set2)	# True

# Built in function method
print(set3.issuperset(set2))	# True

Collection related operations

set1 = {'apple', 'banana', 'pitaya', 'apple'}

# Add element
# Due to the disorder of the collection, append and insert cannot be used, and the position of the element after adding is uncertain
set1.add('grape')
set1.add('durian')
print(set1)	# {'banana', 'pitaya', 'durian', 'grape', 'apple'}

# Delete element
# Deletes the specified element
set1.discard('pitaya')

# Randomly deletes the element, but returns the deleted value
print(set1.pop())	# banana
print(set1.pop())	# durian
print(set1)	# {'grape', 'apple'}

# Empty element
set1.clear()
print(set1)	# set()

# Sets, tuples, and lists can be converted to each other
nums = [1, 1, 10, 10, 10, 5, 3, 9, 9]

# Convert list to collection
set2 = set(nums)
print(set2)	# {1, 3, 5, 9, 10}

# Convert collection to list
list3 = list(set2)
print(list3)	# [1, 3, 5, 9, 10]

# Convert list to tuple
tuple4 = tuple(list3)
print(tuple4)	# (1, 3, 5, 9, 10)

Dictionaries

A preliminary understanding of the dictionary

  1. Store data in key value pairs
  2. The presentation form of data is good
  3. The value can be accurately obtained by pressing the key
  4. Key before: must be of immutable type
  5. Keys can use strings, tuples, and numeric values, but strings take precedence
  6. {} is an empty dictionary
  7. Dictionaries can be nested within a dictionary. The key of the new dictionary is the value of the old dictionary

Construction of dictionary

# Dictionary literal grammar
student = {
    'name': 'Xiao Ming',
    'sex': 'True',
    'birthday': '1999.10.1'
}
print(student)	# {'name': 'Xiaoming', 'sex': True, 'birthday': '1999.10.1'}

# Dictionary constructor syntax
student = dict(name='Xiao Ming', sex=True, birthday='1999.10.1')
print(student)	# {'name': 'Xiaoming', 'sex': True, 'birthday': '1999.10.1'}

# zip the two sequences through Python's built-in function and create a dictionary
items1 = dict(zip('ABCDE', '12345'))
print(items1)	# {'A': '1', 'B': '2', 'C': '3', 'D': '4', 'E': '5'}
items2 = dict(zip('ABCDE', range(1, 10)))
print(items2)	# {'A': 1, 'B': 2, 'C': 3, 'D': 4, 'E': 5}

# Creating dictionaries with dictionary generating syntax
items3 = {x: x ** 3 for x in range(1, 6)}
print(items3)	# {1: 1, 2: 8, 3: 27, 4: 64, 5: 125}

Dictionary operation

student = {
    'name': 'Xiao Ming',
    'sex': 'True',
    'birthday': '1999.10.1'
}

# Dictionary member operation
print('name' in student)	# True
print('birthday' not in student)	# False
print('age' in student)	# False
print(len(student))	# 3

# Index operation of dictionary
# If the index content is not saved, an error will be reported
print(student['name'])	# Xiao Ming

# The dictionary can be modified by index operation
# If the key in the assignment dictionary exists, the original value will be updated, and if it does not exist, a new key value pair will be added
student['name'] = 'Xiao Hong'
student['sex'] = False
student['adresss'] = 'Chengdu, Sichuan'
print(student)	# {'name': 'Xiaohong', 'sex': false, 'birthday': '1999.10.1', 'adress':' Chengdu, Sichuan '}

student['hobby'] = {'comic': 'Luo Xiaohei's War', 'game': 'Empty Knight'}
student['hate'] = {'habit': 'Eat and sound', 'animal': 'mosquito'}
print(student)	# {'name': 'little red', 'sex': false, 'birthday': 'October 1, 1999', 'adress':' Chengdu, Sichuan ',' hobbies': {animation ':' Luo Xiaohei's War record ',' game ':' empty Knight '},' disgust ': {habit': 'eating sound', 'animal': 'mosquito'}}

Operation method of dictionary

# Operation method of dictionary

dict1 = {'a': 1, 'b': 3, 'c': 5, 'd': {'e': 7, 'f': 9}}

# Get the corresponding value through the get () method
# When using the get function to obtain value through key, if the key does not exist, the KeyError error error will not occur, but a None (null value) or the default value specified by you will be obtained
print(dict1.get('a'))	# 1
print(dict1.get('d'))	# {'e': 7, 'f': 9}

# Gets all keys in the dictionary
print(dict1.keys())	# dict_keys(['a', 'b', 'c', 'd'])

# Gets all the values in the dictionary
print(dict1.values())	# dict_values([1, 3, 5, {'e': 7, 'f': 9}])

# Gets all key value pairs in the dictionary
print(dict1.items())	# dict_items([('a', 1), ('b', 3), ('c', 5), ('d', {'e': 7, 'f': 9})])

# Loop through all key value pairs in the dictionary
for key, value in dict1.items():
    print(key, '--->', value)	# a ---> 1	b ---> 3	c ---> 5	d ---> {'e': 7, 'f': 9}
    
# Use the pop method to delete the corresponding key value pair through the key and return the value
stu1 = dict1.pop('d')
print(stu1)	# {'e': 7, 'f': 9}

print(len(dict1))	# 3

stu2 = dict1.pop('', {})
print(stu2)	# {}

# Use the popitem method to delete the last set of key value pairs in the dictionary and return the corresponding binary
# If there is no element in the dictionary, calling this method will throw a KeyError exception
key, value = dict1.popitem()
print(key, value)	# c 5

# Deleting by del does not return data
del dict1['a']
print(dict1)	# {'b': 3}

dict2 = {'A': 100, 'B': 200, 'C': 300}
dict3 = {'D': 400, 'E': 500, 'A': 600}

# Update (merge or update of elements)
dict2.update(dict3)
print(dict2)	# {'A': 600, 'B': 200, 'C': 300, 'D': 400, 'E': 500}

# Find the corresponding value. If the dictionary contains a given key, return the value corresponding to the key; otherwise, return the value set for the key.
print(dict2.setdefault('C'))	# 300
print(dict2.setdefault('K', 10000))	# 10000
print(dict2)	{'A': 600, 'B': 200, 'C': 300, 'D': 400, 'E': 500, 'K': 10000}

# Empty all
dict2.clear()
print(dict2)	# {}	

json

  1. The best choice for exchanging data between two heterogeneous systems is to exchange plain text (which can shield the differences between the system and the programming language)

  2. Plain text should be structured or semi-structured plain text (with a certain format) XML - > extensible markup language - > extensible markup language JSON - > JavaScript object notation - > the data format used by most websites and data interface services YAML —> Yet Another Markup Language
  3. How to convert a string in JSON format into a dictionary in a Python program?
    - > JSON module - > loads function

    The loads function can convert data in JSON format into a dictionary in Python

Trivial knowledge

  1. The criteria for evaluating the algorithm are asymptotic time complexity and asymptotic space complexity

  2. Asymptotic time complexity is marked by O

  3. os stands for operating system

    os.windows('clear ') is used to clear the output

  4. time.sleep() is used to sleep the program

  5. Operating system: Windows, iOS, Android, macOS, Linux, Unix

  6. Programming languages: Python, Java, PHP, Go, C++

  7. URL - > Universal Resource Locator - > uniform resource locator

  8. Protocol - > the session rules that both sides of the communication need to abide by.

  9. HTTP / HTTPS - > protocol for accessing network resources through URL - > Hyper Text Transfer Protocol

  10. request - response

Topics: Python