A dictionary is a unique data type of a Python mapping relationship that consists of paired key values (items).
Items ={' Apple ': ' $ $ ', ' pear ': ' $4 ', ' banana ': ' 6 '}print items[' Apple ']$5
Note that you must use {}, otherwise it becomes a list.
2. Create from list by Dict function
Items =[[' Apple ', ' $],[' pear ', ' $4 '],[' banana ', ' 6 ']]print itemsprint items[0:1]ditems = dict (items) Print Ditemsprint ditems[' apple '][[' apple ', ' $ $ ', [' pear ', ' $4 '], [' Banana ', ' 6 ']][[' apple ', ' $ $ ']]{' pear ': ' $4 ', ' apple ': ' $ $ ', ' banana ' : ' 6 '}$5
1. The key type can be any type, such as float, tuple, string
2. You cannot assign a value to an element outside the index of a list, but you can assign a value directly to a key that is not in the dictionary.
X=[]x[10]=53indexerror:list Assignment index out of rangex={}x[10]= ' "Print x{10: ' 53 '}
3. The in operation checks for key, not value, so it is more efficient.
Example: Building a simple database
#用字典建立一个项目管理数据库Project, key-project name, value contains two dictionaries A and b,key A-project number key B-Project cost
#我们可以使用直接写键值项的方式建立字典, but the amount of data is too large, in order to be concise, first set up lists A and B, respectively, the Dictionary DA and DB, and then through Project keyword parameters P1 and p2 form a large dictionary project
a=[[' npeople ', ' the '],[' ncost ', ' $5000 ']]b=[[' npeople ', ' '],[' ncost ', ' $8000 ']]da=dict (A) (B) print db=dict (DA) Print Dict (DB) p=dict (p1=da,p2=db) print p{' npeople ': ' A ', ' ncost ': ' $5000 '} {' npeople ': ' ' ncost '} ' $8000 ': ' {' Ncost ': ' $8000 ', ' npeople ': ' {'} ', ' P1 ': {' ncost ': ' $5000 ', ' npeople ': ' 12 '}}
Next, you are prompted to enter the project number P1 or P2, check the database for presence, and output the required elements.
a=[[' npeople ', ' the '],[' ncost ', ' $5000 ']]b=[[' npeople ', ' the '],[', ' nCost ', ' $ 8000 ']]da=dict (A) db=dict (B) p=dict (p1=da,p2=db) labels = {' npeople ': ' Number of people ', ' Ncost ': ' cost of money '}id=raw_input (' project id: ' ) request = raw_ Input (' Want to see npeople (p) or ncost (c) ? ') if request == ' P ':key = ' npeople ' if request == ' C ':key = ' Ncost ' If id in P : print "project %s ' s %s is %s." % (Id,labels[key],p[id][key])
Project id:p1want to see Npeople (p) or ncost (c)? Cproject P1 ' s cost of money are $5000.project id:p2want to see Npeople (p) or ncost (c)? Pproject P2 ' s number of people is 15.
Python Learning notes-dictionaries (top)