#!/usr/bin/python#Dictionary#While learning Java, the Language foundation for a long time, and then a variety of APIs, and finally the collection#Key-value pairs, variable#1. Mapping OperationsD= {' Food':'Spam','Quantity': 4,'Color':'Pink'}Print(d[' Food'])#to get a value by keyd['Quantity'] + = 1#change the value corresponding to the key#another way to construct a dictionaryD ={}d['name'] ='Bob'd['Job'] ='Dev'd[' Age'] = 40#The search method written in Python through a dictionary quickly#re-visit nestedRec = {'name': {' First':'Bob',' Last':'Smith'}, 'Job':['Dev','Mgr'], ' Age': 40.5}rec['name']rec['name'][' Last']rec['Job']rec['Job'][-1]#The last value of the list corresponding to the ' job ' keyrec['Job'].append ('Janitor')#None of these objects need to be released manually, there is a Python automatic garbage collection#2. Sort the key: For Loop#dictionaries only support getting elements through keys, and sometimes it's not necessary#For example, to sort a dictionary, get a list of keys and sort by using the Sort method#finally use the For loop to display the results individuallyKs = List (D.keys ())#No list requiredKs.sort ()#to sort keys forKeyinchKs:Print(Key,'=', D[key]) forCinch 'spam': Print(C.upper ()) x= 4 whileX >0:Print('spam!'*x) x-= 1#Iteration and OptimizationSquares= [x * * 2 forXinch[1, 2, 3, 4, 5]]Print(squares) Squares= [] forXinch[1, 2, 3, 4, 5]: squares.append (x* * 2)#list parsing and related function programming tools, such as map and filter, typically run faster than for loops#Start by writing code for simplicity and readability, and then consider the issue after the program can work and verify that it is really necessary to consider performance#about this Python provides time and Timeit and profile modules#non-existent key: if testD= {'a': 1,'C': 3,'b': 2}d['e'] = 99#d[' F ' key ' F ' does not exist, so use will be error-#in relational expressions allow us to query whether a key exists in the dictionaryif not 'F' inchD:Print('missing key F in D') Value= D.get ('x', 0)#gets the value of the key ' x ' if not obtained then is 0 paid valueD[none]= 4#None can also be a key YesPrintD
Python Learning (v) Dictionary learning