directory

  • An introduction to Python dictionary derivations
  • 2.Python dictionary derivation syntax
  • Python dictionary derivation
    • 1. Extract or modify data in the dictionary and return a new dictionary
    • 2. Extract data from the string and return a new dictionary
  • Four. Key summary
  • Five. Guess you like it

Recommended path for learning Python: Python Learning Directory >> Python Basics

An introduction to Python dictionary derivations

In the previous article, we introduced Python conditional and list derivations, which are essentially operations that combine multiple lines of code into one line. Using derivations can make programs run more efficiently.

Python dictionary comprehensions are a way to quickly and succinctly create data types from one or more iterators. They combine loops with conditional judgments to avoid syntactically lengthy code and improve code efficiency. Being able to use derivations is also an indirect indication that you are beyond the beginner level of Python. 六四风波

Python derivations are related:

  • Conditional derivation
  • List derivation
  • Dictionary derivation

2.Python dictionary derivation syntax

Dictionary comprehensions are used in a similar way, using loops and conditional expressions. The difference is that dictionary comprehensions return a dictionary, so the entire expression needs to be written inside {}.

Key: key in the dictionary value: value in the dictionary dict.items() condition: conditional expression key_exp: In the for loop, if the condition is true, return the corresponding key and value and handle value_exp as key_exp,value_exp: In the for loop, if the condition is true, "{key_exp:value_exp for key,value in dict.items() if condition}" Key value: value dict.items() : sequence condition: conditional expression key_exp: In the for loop, if the condition is true, return the corresponding key,value and execute value_exp1 as key_exp,value_exp: In the for loop, if the condition is true, return the corresponding key and value and do key_exp,value_exp1, value_exp2: In the for loop, if the condition is not true (that is, the conditional expression is not true), "{key_exp:value_exp1 if condition else value_exp2 for key,value in dict.items()}Copy the code

Python dictionary derivation

In the following sections, we will use the string conversion/splitting functions. If you are not familiar with them, you should familiarize yourself with the following string operations: Python strings.

1. Extract or modify data in the dictionary and return a new dictionary

#! Usr /bin/env python # -* -coding :utf-8 _*- "" www.codersrc.com @file :Python Python dictionary. Py @time :2021/3/27 08:00 @Motto: A thousand miles without a single step, a river without a small stream, the wonderful life of the program needs to be accumulated with perseverance! "" # Case # 1: Dict1 = {"a":10,"B":20,"C":True,"D":"hello world","e":" Python tutorial "} dict2 = {key:value for key,value in Dict1. Items () if key. Islower ()} print(dict2) # Dict3 = {key.lower():value for key,value in dict1. Items ()} print(dict3) # Dict4 = {key:value if key.isupper() else "error" for key,value in dict1.items()} Dict4) "{key_exp:value_exp1 if condition else value_exp2 for key,value in dict.items()}" 10, 'e' : 'python tutorial'} {10, 'a' : 'b' : 20, 'c' : True, 'd' : 'hello world', 'e' : 'python tutorial'} {' a ':' error ', 'b' : 20, 'c' : True, 'D': 'hello world', 'e': 'error'} ''' {key_exp:value_exp1 if condition else value_exp2 for key,value in dict.items()} '''Copy the code

2. Extract data from the string and return a new dictionary

In the later crawler course, we need to obtain cookies and pass them in the form of dictionaries. If cookies are strings, we need to convert them into dict dictionaries. The classic code cases are as follows:

#! Usr /bin/env python # -* -coding :utf-8 _*- "" www.codersrc.com @file :Python Python dictionary. Py @time :2021/3/27 08:00 @Motto: A thousand miles without a single step, a river without a small stream, the wonderful life of the program needs to be accumulated with perseverance! """ cookies = "anonymid=jy0ui55o-u6f6zd; depovince=GW; _r01_=1; JSESSIONID=abcMktGLRGjLtdhBk7OVw; ick_login=a9b557b8-8138-4e9d-8601-de7b2a633f80; _ga = GA1.2.1307141854.1562980962; _gid = GA1.2.201589596.1562980962; _c1=-100; first_login_flag=1; ln_uact=18323008898; ln_hurl=http://head.xiaonei.com/photos/0/0/men_main.gif; jebe_key=88f1340c-592c-4dd6-a738-128a76559f45%7Cad33b3c730fcdc8df220648f0893e840%7C1562981108370%7C1%7C1562981106763; jebe_key=88f1340c-592c-4dd6-a738-128a76559f45%7Cad33b3c730fcdc8df220648f0893e840%7C1562981108370%7C1%7C1562981106765; jebecookies=793eb32e-92c6-470d-b9d0-5f924c335d30|||||; _de=E77807CE44886E0134ABF27E72CFD74F; p=a00d65b1f779614cd242dc719e24c73e0; t=292ba8729a4151c1a357e176d8d91bff0; societyguester=292ba8729a4151c1a357e176d8d91bff0; id=969937120; xnsid=1700b2cc; Ver = 7.0; loginfrom=null; Wp_fold =0" # dictionary derived cookies = {cookie.split("=")[0]:cookie.split("=")[1] for cookie in cookie.split("; ")} print (cookies) "' output: {' anonymid ':' jy0ui55o - u6f6zd ', 'depovince' : 'GW', '_r01_' : '1', 'JSESSIONID' : 'abcMktGLRGjLtdhBk7OVw', 'ick_login': 'a9b557b8-8138-4e9d-8601-de7b2a633f80', '_ga': 'GA1.2.1307141854.1562980962', '_gid' : 'GA1.2.201589596.1562980962', '_c1' : '100', 'first_login_flag' : '1', 'ln_uact' : '18323008898', 'ln_hurl': 'http://head.xiaonei.com/photos/0/0/men_main.gif', 'jebe_key': '88f1340c-592c-4dd6-a738-128a76559f45%7Cad33b3c730fcdc8df220648f0893e840%7C1562981108370%7C1%7C1562981106765', 'jebecookies': '793eb32e-92c6-470d-b9d0-5f924c335d30|||||', '_de': 'E77807CE44886E0134ABF27E72CFD74F', 'p': 'a00d65b1f779614cd242dc719e24c73e0', 't': '292ba8729a4151c1a357e176d8d91bff0', 'societyguester': '292 ba8729a4151c1a357e176d8d91bff0', 'id', '969937120', 'xnsid' : '1700 b2cc', 'ver' : '7.0', 'loginfrom' : 'null', 'wp_fold': '0'} '''Copy the code

Code analysis:

In string cookies, ‘=’ is preceded by key and ‘=’ is followed by value, each ‘; ‘form a key-value pair; Multiple key-value pairs form a dictionary;

  • 1. According to the ‘; ‘Splits a string into a list;
  • 2. According to the list obtained in the first step, the traversal will split each string according to ‘=’ again;
  • 3. According to the split result in step 2, the first element of the list is used as the key and the second element of the list is used as the value;

Four. Key summary

Python dictionary derivations and list derivations are both more efficient than regular for loops. Python list derivations are tested at the end of the article.

Note the difference between dictionary and list derivations:

  • 1. List comprehensions return lists with expressions in brackets []
  • 2. Dictionary comprehensions return dictionaries with expressions in braces {}

Five. Guess you like it

  1. Python Configuration Environment
  2. Python variable
  3. Python operator.
  4. Python conditions determine if/else
  5. Python while loop
  6. Python break
  7. Python continue
  8. The Python for loop
  9. The Python string
  10. The Python list
  11. The Python tuple tuple
  12. Python dictionary dict
  13. Python conditional derivations
  14. Python list derivations
  15. Python dictionary derivations

Python dictionary derivations

This article is published by the blog – Ape Say Programming Ape Say programming!