1 unpacked

By unpacking dictionaries, we convert them to Key=Value via the ** operator, which can be passed directly to functions as keyword arguments. Talk about some of the situations that apply.

1.1 Search for Splicing conditions

When an application reads data using an ORM format similar to SQLAlchemy, the search parameters passed into the ORM change depending on the search criteria. Here are some of the book table data (only some of the fields are shown)

+----+---------------+-------------------------+-------+ | id | category_name | book_name | price | + - + -- -- -- -- -- -- -- -- -- -- -- -- -- -- - + -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - + -- -- -- -- -- -- -- + | 1 | | human history of humanities social sciences 42.90 | | | 2 | | the world history of humanities social sciences 25.50 | | | | 3 Economic management | acme 37.00 | products | | | | 4 economic management Steve jobs 44.20 | | | | 5 economic management | | | 41.20 influence +----+---------------+-------------------------+-------+Copy the code

When searching, we execute the query method in this form

books = Book.query.filter_by(id=1, book_name='influence').all()
Copy the code

However, because the incoming parameters will change according to the change of the search criteria, you cannot write the parameters directly. In this case, you can use the dictionary to unpack

condition = {}
if book_id:
	condition['id'] = id
if book_name:
	condition['name'] = book_name
books = Book.query.filter_by(**condition).all()
Copy the code

That’s OK

1.2 Method parameters too many, for code aesthetic use

new_book = Book(category_name='Literary fiction', book_name='Sorrow Grocery store', price = 28.8,...). db.session.add(new_book)Copy the code

If I change it to something like this, it looks nice

book_param = {'category_name': 'Literary fiction'.'book_name': 'Sorrow Grocery store'.'price': 28.8,
			  ...}
new_book = Book(**book_param)
db.session.add(new_book)
Copy the code

In addition, in the above process of adding books, the submitted parameters are verified, and the result returned by the verification method (that is, book_param and other information) is usually a dictionary, so using the dictionary to unpack is more realistic.

In summary, the proper use of dictionary unpacking to pass parameters to methods can make our code more flexible.

2 the use of setdefault()

So let’s see how this works, right

dict.setdefault(key, default=None)

Returns the value of the given key if it is contained in the dictionary, otherwise returns the value set for that key.

Many times we need to convert a list to a dictionary containing the list based on a key of the element. For example, in the above data, I want to get a dictionary, the key of the dictionary is the book category, and the value is the list of books belonging to the category. We usually write it like this

books_dict = {}
for book in book_list:
    if book['category_name'] not in books_dict.keys():
        books_dict[book['category_name']] = []
    books_dict[book['category_name']].append(book)
Copy the code

And, of course, this is the right way to write it, to get the desired result

{
	"Humanities and Social Sciences": [{
		"id": 1,
		"category_name": "Humanities and Social Sciences"."book_name": "A Brief History of Mankind."."price": 42.9}, {"id": 2."category_name": "Humanities and Social Sciences"."book_name": "A Brief History of the World."."price"] : 25.5},"Economic management": [{
		"id": 3."category_name": "Economic management"."book_name": "The ultimate product"."price": 37.0}, {"id": 4."category_name": "Economic management"."book_name": "The Biography of Steve Jobs"."price": 44.2}, {"id": 5,
		"category_name": "Economic management"."book_name": "Influence"."price"] : 41.2}}Copy the code

But if you use the dictionary setdefault() method, you can write fewer lines of code and look more elegant

books_dict = {}
for book in book_list:
    books_dict.setdefault(book['category_name'], []).append(book)
Copy the code

3 Dictionary Merge

Common merge methods

# new_dict = {**dict1, **dict2, ... }
# merge multiple dictionaries. If the same key exists in the dictionary, the last one overwrites the previous one
Dict2 overwrites the same value of key in dict1

>>> a = {'name': 'x'.'age': 13}
>>> b = {'name': 'y'}
>>> c = {**a, **b}
>>> c
{'name': 'y'.'age'13} :# dict1.update(dict2)
# Merge the two dictionaries. If the same key exists in the dictionary, dict2 will overwrite the corresponding value of dict1
Update a dictionary

>>> a.update(b)
>>> a
{'name': 'y'.'age'13} :Copy the code

Sometimes we come across dictionaries that are merged. For example, we are going to create a new book based on the basic information of a book

# to_dict Converts ORM objects into dictionaries
base_book = Book.query.filter_by(id=1).first().to_dict()
The returned value contains book_param, similar to the following
book_param = {'book_name': 'National Treasure'.'price': 55.60}
Update the creation time and update time of the new book
time_param = {'created_at': current_time, 'updated_at': current_time}
# New books
new_book = Book(**{**base_book, **book_param, **time_param})
db.session.add(new_book)
Copy the code

Of course, you can also use the update() method if you just merge two dictionaries.

Suppose we just need to merge base_book and book_param

base_book.update(book_param)
Copy the code

This also works, but be aware that it changes the values in base_book.

If you are simply updating a dictionary, the update() method is obviously best. For current requirements, the first approach is more appropriate.

This article is published on the public account “small back end”, follow and reply to the keyword “1024”, all kinds of IT learning materials gift package for free.