Use of the Python dictionary

Source: Internet
Author: User

Dictionary:

#可以用大括号创建字典, can also be created with the factory function; cleese={} palin=dict () #给字典加入一些数据cleese [' Name '] = ' John Cleese ' cleese[' occupations '] = [' actor ', ' comedian ', ' writer ',] #查看里面有哪些数据项In [9]: Cleeseout[9]: {' Name ': ' John Cleese ', ' occupations ': [' actor ', ' comedian ', ' Writer ']}palin = {' Name ': ' Michael Palin ', ' occupations ': [' comedian ', ' actor ', ' writer ', ' TV ']}in [all]: palinout[11]: {' Name ': ' Michael Palin ', ' occupations ': [' comedian ', ' actor ', ' writer ', ' TV ']} #可以通过键来调用对应的数据In []: palin[' Name ']out[13 ]: ' Michael Palin ' #如果字典中一个键对应着多个数据项 can also be accessed using a list-like notation. In [all]: palin[' occupations '][-1]out[15]: ' TV ' in [+]: palin[' occupations '][1]out[16]: ' actor ' in [+]: palin[' Occupations '][0]out[17]: ' Comedian '

First, the following data processing, the output to retain the names of people and match data sorted by the top three items.

Sarah sweeney,2002-6-17,2:58,2.58,2:39,2-25,2-25,2:54,2.18,2:55,2:55

First edition code:

#!/usr/local/python3/bin/python3def sanitize (time_string):    if  '-'  in  time_string:        splitter= '-'     elif   ': '  in time_string:        splitter= ': '      else:        return (time_string)      ( Mins,secs)  = time_string.split (splitter)     return (mins +  '. ')  + SECS) def get_file_data (filename):    try:         with open (filename)  as f:             data = f.readline ()         return ( Data.strip (). Split (', '))     except IOError as ioerr:         print (' FILE&NBsp;error '  + str (ioerr))         return (None) sarah1 =  get_file_data (' Sarah2 ') #这里是将列表中前两项数据, names and birthdays pop into Sarah_name,sarah_dob two variables using pop. (SARAH_NAME,SARAH_DOB)  = sarah1.pop (0), Sarah1.pop (0) #这里要做字符串拼接, so after the subsequent sequence processing, you need to use STR () to convert to a string. Print (sarah_name +  "' S fastest times are:"  + str (Sorted (set ([ sanitize (i)  for i in sarah1 ])) [0:3]))

Output Result:

Sarah Sweeney ' s fastest times are:[' 2.18 ', ' 2.25 ', ' 2.39 '


Second, the function defined above is the same, we use the dictionary to complete the way

Second Edition code:

#!/usr/local/python3/bin/python3def sanitize (time_string):    if  '-'  in  time_string:        splitter= '-'     elif   ': '  in time_string:        splitter= ': '      else:        return (time_string)      ( Mins,secs)  = time_string.split (splitter)     return (mins +  '. ')  + SECS) def get_file_data (filename):    try:         with open (filename)  as f:             data = f.readline ()         return ( Data.strip (). Split (', '))     except IOError as ioerr:         print (' FILE&NBsp;error '  + str (ioerr))         return (None) sarah1 = The  get_file_data (' SARAH2 ') #定义字典sarah_dic the =dict () #将列表中前两个数据项, and the popup is saved to the corresponding key in the dictionary. sarah_dic[' name '] = sarah1.pop (0) sarah_dic[' dob '] = sarah1.pop (0) #姓名和日期都弹出了, The rest of the SARAH1 is the time data, saved in the Sarah_dic dictionary, the key is time;sarah_dic[' Times '] = sarah1print (sarah_dic[' name '] +   "' s fastest time are: "  + str (sorted (Set ([Sanitize (i)  for i  IN SARAH1])) [0:3])

The output is the same as above


Third, move the creation of the dictionary to the Get_file_data () function and return a dictionary instead of a list. And the data slice, to repeat the item, the sort also moves to the Get_file_data function, calls the function completes 4 contestant's achievement output.

The third version of the Code:

#!/usr/local/python3/bin/python3def sanitize (time_string):    if  '-'  in  time_string:        splitter= '-'     elif   ': '  in time_string:        splitter= ': '      else:        return (time_string)      ( Mins,secs)  = time_string.split (splitter)     return (mins +  '. ')  + SECS) def get_file_data (filename):    try:         with open (filename)  as f:             data = f.readline ()         templ  = data.strip (). Split (', ')         return ({' Name ': Templ.pop (0 ),       &Nbsp;          ' DOB ': Templ.pop (0),                  ' time ': Str (sorted (Set ([Sanitize (i)  for  i in templ]) ([0:3])})     except IOError as ioerr:         print (' File error '  + str (ioerr))          return (None) james1 = get_file_data (' James2 ') julie1 = get_ File_data (' Julie2 ') mikey1 = get_file_data (' Mikey2 ') sarah1 = get_file_data (' Sarah2 ') print ( james1[' name '] +  "' s fastest time are: "  + james1[' time ']) print (julie1 [' Name '] +  ' s fastest time are:  '  + julie1[' time ']) print (mikey1[' name '] +  ' ' s fastest time are:  '  + mikey1[' time ') print (sarah1[' name ')  +  "' S fastest time are:   + sarah1[' time ') 

Output Result:

650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M01/70/3F/wKiom1W07--wD7nnAADf4Gtbl_Y958.jpg "title=" 1234. PNG "alt=" wkiom1w07--wd7nnaadf4gtbl_y958.jpg "/>


Difficulties:

Def get_file_data (filename):    try:         With open (filename)  as f:             data = f.readline ()         templ =  Data.strip (). Split (', ') #可以看到这里是返回字典了, found that even the dictionary name is not, directly return the key and the corresponding data.                 return ({' Name ' : Templ.pop (0),                 ' DOB ': Templ.pop (0),                  ' time ': Str (sorted (Set ([Sanitize (i)  for i in templ]) [0:3])})      Except ioerror as ioerr:        print (' File error '  + str (Ioerr))         reTurn (None)          #由于返回过来的直接是字典数据, here, with any variable function, will become a dictionary, The data corresponding to the function return key value is stored in the dictionary. James1 = get_file_data (' James2 ')      #这里就可以使用字典和键 ' james1[' name '] "to output the data. Print (james1[' name '] +  "' s fastest time are: "  + james1[' time '])


This article is from the "Break Comfort zone" blog, so be sure to keep this source http://tchuairen.blog.51cto.com/3848118/1678551

Use of the Python dictionary

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.