Python:dict Study Notes

Source: Internet
Author: User

Dict full name dictionary, using key-value (key-value) storage, there is a very fast search speed.

Here are some common dict usage

Defined

>>> dict={}>>> dict={'Adele':'Hello','Taylor':'1989'}>>>dict{'Taylor':'1989','Adele':'Hello'}

Nesting

>>> A_dict={1:"{one: ' A ', ': ' B '}", 2:"2B", 3:"3C"}>>>a_dict{1:"{one: ' A ', ': ' B '}", 2:'2B', 3:'3C'}>>> a_dict[1][12]'b'

Gets the key, value

>>>A_dict.keys () [1, 2, 3]#The result is a list>>>a_dict.values () ["{one: ' A ', ': ' B '}",'2B','3C']>>>A_dict.items () [(1,"{one: ' A ', ': ' B '}"), (2,'2B'), (3,'3C')]#The result is that the elements inside the list,list are tuples>>> forKeyincha_dict: ...Print(key) ...123>>> forValueincha_dict.values (): ...Print(value) ... {11:'a', 12:'b'}2b3c>>> forKeyincha_dict: ...PrintA_dict[key] ... {11:'a', 12:'b'}2b3c>>> forKvinchA_dict.items (): ...PrintSTR (k) +":"+Str (v) ...1:{11:'a', 12:'b'}2: 2B3: 3C>>> forKincha_dict: ...PrintSTR (k) +":"+str (a_dict[k]) ...1:{11:'a', 12:'b'}2: 2B3: 3C>>> forKincha_dict: ...Print "a_dict (%s) ="%K,a_dict[k] ... a_dict (1) = {11:'a', 12:'b'}a_dict (2) =2ba_dict (3) =3C>>> A_dict.get (1)"{one: ' A ', ': ' B '}"

Delete

>>> A_dict.pop ('Taylor')'1989'  #Delete based on key value, and return value>>>delA_dict[1]>>>a_dict{2:'2B', 3:'3C','Adele':'Hello'}>>>a_dict.clear ()>>>a_dict{}

Copy

>>> new_dict=a_dict.copy ()>>> new_dict{"{one: ' A ', ' B '} " ' 2B ' ' 3C '}

Merge

>>> add_dict={'Adele':'Hello','Taylor':'1989'}>>>a_dict.update (add_dict)>>>a_dict{1:"{one: ' A ', ': ' B '}", 2:'2B', 3:'3C','Adele':'Hello','Taylor':'1989'}

Sort

>>>PrintSorted (A_dict.items (), key=LambdaD:d[0]) [(1,"{one: ' A ', ': ' B '}"), (2,'2B'), (3,'3C')]#Sort by Key>>>PrintSorted (A_dict.items (), key=LambdaD:d[1])[(2,'2B'), (3,'3C'), (1,"{one: ' A ', ': ' B '}")]#Sort by Value

Subsequent use, add:

Python:dict Learning Notes

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.