On Python in the dictionary scattered mass participation

The actual development, we often encounter operational data submitted by the user after checking into the database.
Suppose the user form to post form submission data into the Customer table, the background data is received is often carried out by treatment:

# 将csrf校验的键值对去除
request.POST.pop("csrfmiddlewaretoken")
# 以打散的方式将数据传入数据库的表中
Customer.objects.update_or_create(**request.POST)

We know, request.POST is a QueryDicttarget, in fact it is a custom 字典, in addition to modify the time to note that 不可变特性other than during parameter passing when we can use it as a dictionary.
But also it noted that this "break up" approach requires the mass participation 字典of all in keymust be consistent with the name of the table in the database fields! Otherwise, parameter passing when an error occurs!

A small demo to explain the mechanism of the dictionary scattered parameter passing

So the question is: this 打散what mechanism the way it is?
Consider the following example:

def func(username,password):
    global count
    print(count,username,password)
    count += 1

if __name__ == '__main__':
    count = 1
    dic = {"username":'whw','password':123}
    # 打散传参与位置参数传参
    func(**dic)
    func(username='whw',password=123)

Implementation of the results are as follows:

1 whw 123
2 whw 123

First, let's define a function func, there are two position parameters username and password, and then define a dictionary dic={"username":"whw","password":123}, count variable used as a counter.
Then, when we perform the function func used two ways to pass parameters: only one kind of **dicway, that is, dic beaten; the other is the conventional way to pass parameters.
Both methods normally performed, transmission parameters described above two are equivalent to!
In other words: **dicThe dictionary 打散became one of key=valuethe form!
In addition, the need to pay special attention to the point: This parameter passing mode key for the dictionary is required, the dictionary was beaten key value must match the value of the location parameter function, otherwise the program will complain!

Guess you like

Origin www.cnblogs.com/paulwhw/p/11328628.html