Python learning content. 05

Source: Internet
Author: User

The main contents of this section:
1. A simple introduction to the dictionary 2. Dictionary additions and deletions and other operations 3. Nesting of dictionaries
I. The dictionary's Simple Introduction Dictionary (dict) is the only type of mapping in Python. He is composed of key-value pairs enclosed in {}. In Dict, key is unique. At the time of saving, a memory address is calculated based on key. Then save the Key-value in this address. This algorithm is called the hash algorithm, so, remember, in the dict stored in the Key-value key ' must be hash, if you do not understand what is hash, temporarily can remember, can change is not hash, then the hash means immutable. This is required to be able to accurately calculate the memory address.
Known hash (immutable) data types: int, str, tuple, bool non-hash (variable) data type: List, Dict, set
Syntax: {key1:value1, key2:value2 ...}
Note: Key must be immutable (hashed). value is not required. Can save any type of data
# legal dic = {123:456, true:999, "id": 1, "name": ' Sylar ', "age": 2, "Stu": [' Handsome ', ' Beauty '], (1,, 3): ' Twist Vine '} print (dic[123 ] Print (Dic[true]) print (dic[' id ') print (dic[' Stu ') print (dic[(1, 2, 3)]) # illegal # dic = {[1, 2, 3]: ' Jay Chou '} # list is mutable . cannot be as key # dic = {{1:2}: "Hahaha"} # Dict is mutable. cannot be as key dic = {{1, 2, 3}: ' Hehe '} # set is mutable and cannot be a key
The data saved by Dict is not saved in the order we added. are stored in the order of the hash table. And the hash table is not continuous. So you can't do the slicing work. It can only get the data in Dict by key
Two. Dictionary additions and deletions and other related operations
1. Increase
DIC = {} dic[' name '] = ' Chow Yun Fat ' # If this key is not present in Dict, a key-value combo will be added dict dic[' age ' = print (DIC)
# If this key-value has not been seen in Dict. You can set the default value via SetDefault dic.setdefault (' Li Ka Shing ') # or you can set the value inside. Dic.setdefault ("Li Ka-shing", "Real Estate") # if dict already exists. Then SetDefault will not work.
Print (DIC)
2. Delete
ret = Dic.pop ("Jay") print (ret)
Del dic["Jay"] Print (DIC)
# randomly deleted. ret = Dic.popitem ()
# empty everything in the Dictionary dic.clear ()
3. Modifications
DIC = {"id": 123, "name": ' Sylar ', "Age": dic1} = {"id": 456, "name": "Twist Vine", "OK": "WTF"} dic.update (Dic1) # put Dic1 Content to be updated in DIC. If the key is duplicate. The replacement is modified. If there is no key, it is added. Print (DIC) print (DIC1)
4. Enquiry
Queries typically use key to find specific data.
Print (dic[' name ']) # print (dic[' Sylar ') # Error print (Dic.get ("OK")) Print (Dic.get ("Sylar")) # None print (Dic.get (" Sylar "," Ox B ")) # Bull B
5. Other related operations

DIC = {"id": 123, "name": ' Sylar ', "age": "OK": "Kobe"}
Print (Dic.keys ()) # Dict_keys ([' id ', ' name ', ' age ', ' OK ') do not care what it is. Use as a list for key in Dic.keys (): Print (key)
Print (Dic.values ()) # dict_values ([123, ' Sylar ', 18, ' Kobe ']). Also when list comes with for value in Dic.values (): Print (value)
Print (Dic.items ()) # dict_items ([' id ', ' 123 '), (' Name ', ' Sylar '), (' Age ', ' + '), (' OK ', ' Kobe ')]) This thing is also a list. Only the list is loaded with a tuple for key, the value in Dic.items (): #?? This is deconstructed print (key, value)
# deconstructed A, B = 1, 2 print (A, B)
(c, D) = 3, 4 print (C, D)
E, F = [1, 2, 3] # when deconstructed, note quantity must match print (E, f)
Three. Nested Dic1 of the dictionary nested # dictionary = {"name": "Wang Feng", "Age": "Wife": {"name": ' Zhang Ziyi ', "age":--}, "Chi Ldren ": [' First Kid ', ' Second Kid ']," desc ": ' Feng brother will not sue me. Never mind. I want to be on the headline '}
Print (Dic1.get ("wife"). Get ("name")) Print (Dic1.get ("Children")) Print (Dic1.get ("Children") [1])
Exercise: Dic1 = {' name ': [' Alex ', 2,3,5], ' job ': ' Teacher ', ' Oldboy ': {' alex ': [' python1 ', ' python2 ', 100]}} 1, the column that corresponds to name The table appends an element of ' Wusir '. 2, capitalize the Alex initials in the list that corresponds to name. 3,oldboy corresponding dictionary plus a key value to ' old boy ', ' Linux '. 4, remove Python2 from the corresponding list of Alex in the Oldboy corresponding dictionary

Homework:

, the following variables (TU is a meta-ancestor), please implement the required functions
Tu = ("Alex", [One, one, 11, {"K1": ' V1 ', "K2": ["Age", "name"], "K3": (, 22, 33)}, 44])
A. Describe the characteristics of ganso; A: Ganso () is a read-only list that can index slices, loops, iterations, but cannot be censored.
B. May I ask whether the first element of the TU variable "Alex" can be modified? A: cannot be modified
C. What is the value of "K2" in the TU variable? Is it possible to be modified? If you can, add an element, "Seven", to the
The corresponding value of "K2" is the list type data, which can be changed. "
tu[1][2]["K2"]=["Age", "name", "Seven"]
Print (TU)
D. What is the value of "K3" in the TU variable? Is it possible to be modified? If you can, add an element, "Seven", to the
The value of "K3" is ganso and cannot be modified.
2, dictionary dic, dic = {' K1 ': "v1", "K2": "V2", "K3": [11, 22, 33]}

A. Please loop out all the keys
Print (Dic.keys ())
B. Please loop out all the value
Print (Dic.values ())
C. Please loop out all the keys and value
For a In Dic.keys ():
Print (a)
Print (Dic.get (a))
D. Add a key-value pair in the dictionary, "K4": "V4", and output the added dictionary
dic["K4"]= "v4"
Print (DIC)
E. In the modified dictionary, the value of "K1" corresponds to "Alex", Output the modified dictionary
dic["K1"]= "Alex"
Print (DIC)
F. Please append an element 44 to the value of the K3, and output the modified dictionary
dic["K3"]=[11, 22, 33,44]
Print (DIC)
G. Insert element 18 in the 1th position of the K3 corresponding value, output the modified dictionary
dic["K3"]=[11,18, 22, 33,]
Print (DIC)
3,av_catalog = {
"Europe and America": {
"Www.youporn.com": ["a lot of free, the world's largest", "General quality"],
"Www.pornhub.com": ["a lot of free, also very big", "quality than Yourporn high"],
"Letmedothistoyou.com": ["mostly selfie, high-quality pictures many", "resources are not many, update slow"],
"X-art.com": ["high quality, really high", "all charges, cock wire please bypass"]
},
"Japan and Korea": {
"Tokyo-hot": ["How the quality is not clear, the individual has not liked Japan and South Korea fan", "Verygood"]
},
"Continent": {
"1024": ["All free, really good, good Life Peace", "server in foreign countries, slow"]
}
}

A, give this ["a lot of free, the world's largest", "Quality General"] list the second position inserts an element: ' Very large '.
av_catalog["Europe and America"] ["www.youporn.com"]= "a lot of free, the world's largest", "Quality General", "large quantity"
Print (Av_catalog)
b, will this ["high quality, really high", "all charges, the cock wire please bypass"] List of "All charges, cock wire please bypass" delete.
av_catalog["Europe and America" ["x-art.com"]= "high quality, really high"
Print (Av_catalog)
c, will this ["The quality is very high, really high", "all charges, the cock wire please bypass"] List of the "all charges, cock wire please bypass" delete.
av_catalog["Europe and America" ["x-art.com"]= "high quality, really high"
Print (Av_catalog)
D, this ["How quality is unclear, the individual has not liked Japan and South Korea fan", "Verygood"] List of "Verygood" all become uppercase.
av_catalog["Japan and Korea" ["Tokyo-hot"][1]=av_catalog["Japan and Korea"] ["Tokyo-hot"][1].upper ()
Print (Av_catalog)
E, add a key-value pair ' 1048 ' to the dictionary corresponding to ' continent ': [' One day is sealed ']
av_catalog["mainland" ["1048"]= "a day is sealed"
Print (Av_catalog)
F, delete this "letmedothistoyou.com": ["mostly selfie, high-quality pictures many", "Resource not much, update slow"] key value pairs.
Del av_catalog["Europe and America" ["letmedothistoyou.com"]
Print (Av_catalog)
G, give this ["All free, really good, a good Life Peace", "server in Foreign, slow"] list of the first element, plus a sentence: ' Can climb down '
av_catalog["mainland" ["1024"][1]= "server is abroad, slow, can climb down"
Print (Av_catalog)
4. The string "K:1|k1:2|k2:3|k3:4" is processed into a dictionary {' K ': 1, ' K1 ': 2 ...}
S=a.split ("|")
dic={}
For S1 in S:
Dic[s1.split (":") [0]]=int (S1.split (":") [1])
Print (DIC)

5, the element classification has the following values Li = [11, 22, 33, 44, 55, 66, 77, 88, 99, 90], will all be greater than 66
Value to the first key in the dictionary, and the value less than 66 is saved to the value of the second key. That is: {' K1 ': List of all values greater than 66, ' K2 ': List of all values less than 66}
Li = [11, 22, 33, 44, 55, 66, 77, 88, 99, 90]
Li1=[]
Li2=[]
dic={' K1 ': "List of all values greater than 66,", ' K2 ': "List of all values less than 66"}
For a in Li:
If a >66:
Li1.append (a)
Else
Li2.append (a)
dic["K1"]=str (LI1)
dic["K2"]=str (LI2)
Print (DIC)
6, the output product list, the user enters the serial number, displays the user to select the product

Product List:
Goods = [{"Name": "Computer", "Price": 1999},
{"Name": "Mouse", "Price": 10},
{"Name": "Yacht", "Price": 20},
{"Name": "Beauty", "Price": 998},]

Requirements:
1: Page display serial number + product name + commodity price, such as: 1 Computer 1999
2 Mouse 10 ...
2: The user enters the selected product serial number, then prints the product name and the commodity price
3: If the user entered an incorrect serial number, you are prompted to enter it incorrectly and re-enter it.
4: User input Q or q, exit the program.










The content of tomorrow's dictation.

1) dictionary additions and deletions to the search.
2) filter the sensitive character code of the dictation.

Li = ["Cang teacher", "Tokyo Fever", "Enrique", "Yui Hatano")
L1 = []
Comment = input (' Please enter comment >>> ')
For I in Li:
If
I in Comment:
Comment = Comment.replace (i, ' * ' * len (i))
L1.append (comment)
Print (L1)

Python learning content. 05

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.