Reading notes--second edition of the basic Python tutorial--fourth dictionary: When the index is not good

Source: Internet
Author: User
Tags shallow copy

The key in the dictionary can be a number, a string, a tuple

4.1 Use of the dictionary


>>> name=[' Alice ', ' Beth ', ' Earl '

>>> numbers=[' 2341 ', ' 9102 ', ' 0142 '] #电话号码必须使用字符串, two cannot be integers, because the phone number may start with 0

>>> numbers[name.index (' Beth ')]

' 9102 '



4.2 Creating and using dictionaries

>>> data ={' title ': ' My home Page ', ' text ': ' Welcome to My home page! '}


4.2.1 Dict function

Create a dictionary from another mapping, or a sequence of key values

>>> items=[(' name ', ' Gumby '), (' Age ', 42)]

>>> d=dict (items)

>>> D

{' Age ':, ' name ': ' Gumby '}

>>> d[' name ']

' Gumby '


Create dictionaries directly with dict, using key-value pairs, or mappings and keyword parameters to create dictionaries

>>> d = dict (name= ' Gumby ', age=42)

>>> D

{' Age ':, ' name ': ' Gumby '}

The Dict function is similar to the tuple and STR functions

>>> c=dict ()

>>> C

{}


4.2.2 Basic Dictionary Operations

Len (d) Returns the number of key-value pairs in D

D[K]

D[k]=v

Del D[k]

K in D check if D contains K

>>> D

{' Age ':, ' name ': ' Gumby '}

>>> Len (d)

2

>>> d[' age ']

42

>>> d[' age ']=35

>>> D

{' Age ': +, ' name ': ' Gumby '}

>>> ' age ' in D

True

>>> ' Age1 ' in D

False

>>> del d[' age ']

>>> D

{' name ': ' Gumby '}


Comparison of dictionaries and lists

1, the key type most commonly used is the string and the tuple

2. Automatically add list assignment must initialize list

3, membership, dictionary lookup is the key, the list looks for the value




Formatted string for 4.2.3 Dictionary

>>> phonebook={' Beth ': ' 9102 ', ' Alice ': ' 2341 ', ' Cecil ': ' 3258 '}

>>> "Cecil ' s phone number is% (Cecil) s."% phonebook

"Cecil ' s phone number is 3258."




>>> data ={' title ': ' My home Page ', ' text ': ' Welcome to My home page! '}

>>> template= '

...

... <body>

...

... <p>% (text) s</p>

... </body> "

>>> Print Template% data

<body>

<p>welcome to my home page!</p>

</body>



4.2.4 Dictionary method

1. Clear returns None

>>> d[' name ']= ' Gumby '

>>> D.clear ()

>>> D

{}

Application One:

>>> x = {}

>>> y = x

>>> x[' key ']= ' value '

>>> y

{' key ': ' Value '}

>>> x

{' key ': ' Value '}

>>> x={}

>>> y

{' key ': ' Value '}

>>>


Application Two

>>> x = {}

>>> y = x


>>> x[' key ']= ' value '

>>> x

{' key ': ' Value '}

>>> y

{' key ': ' Value '}

>>> X.clear ()

>>> x

{}

>>> y

{}




2, copy shallow copy, modify the reference type of key, the original dictionary has an impact



>>> x={' username ': ' admin ', ' machines ': [' foo ', ' Bar ', ' Baz ']}

>>> y=x.copy ()

>>> y[' username ']

' Admin '

>>> x[' username ']

' Admin '


>>> y[' username ']= ' MLH '

>>> y[' machines '].remove (' bar ')

>>> y

{' username ': ' MLH ', ' Machines ': [' foo ', ' Baz ']}

>>> x

{' username ': ' admin ', ' machines ': [' foo ', ' Baz '}}


Deepcopy Deep Copy


>>> from copy import deepcopy

>>> d={}

>>> d[' names ']=[' Alfred ', ' Bertrand ']

>>> c=d.copy ()

>>> Dc=deepcopy (d)

>>> d[' names '].append (' Clive ')

>>> C

{' names ': [' Alfred ', ' Bertrand ', ' Clive ']}

>>> D

{' names ': [' Alfred ', ' Bertrand ', ' Clive ']}

>>> DC

{' names ': [' Alfred ', ' Bertrand ']}


3. Fromkeys Create a new dictionary with the given key

>>> {}.fromkeys ([' Name ', ' age '])

{' Age ': none, ' Name ': none}

>>> Dict.fromkeys ([' Name ', ' age '])

{' Age ': none, ' Name ': none}

>>> Dict.fromkeys ([' Name ', ' age '], ' (unkown) ')

{' Age ': ' (unkown) ', ' Name ': ' (unkown) '}



4, get, access not to error



>>> d={}

>>> print d[' name ']

Traceback (most recent):

File "<stdin>", line 1, in <module>

Keyerror: ' Name '

>>> print d.get (' name ')

None

>>> print d.get (' name ', ' N/A ')

N/A

>>> d[' name ']= ' Eric '

>>> print d.get (' name ', ' N/A ')

Eric



5, Has_key equivalent to K in D


>>> d={}

>>> d.has_key (' name ')

False

>>> d[' name ']= ' Eric '

>>> d.has_key (' name ')

True


6. Items and Iteritems return the dictionary as a list


>>> d={' title ': ' Python Web site ', ' url ': ' http://www.python.org ', ' spam ': ' 0 '}


>>> D.items ()

[(' url ', ' http://www.python.org '), (' Spam ', ' 0 '), (' title ', ' Python web site ')]

>>> D

{' URL ': ' http://www.python.org ', ' spam ': ' 0 ', ' title ': ' Python Web site '}

>>> It=d.iteritems ()

>>> it

<dictionary-itemiterator Object at 0x7fe272022af8>

>>> list (IT) #将迭代器转换为list

[(' url ', ' http://www.python.org '), (' Spam ', ' 0 '), (' title ', ' Python web site ')]



7. Keys and Iterkeys


>>> D

{' URL ': ' http://www.python.org ', ' spam ': ' 0 ', ' title ': ' Python Web site '}

>>> D.keys ()

[' url ', ' spam ', ' title ']

>>> Ks=d.iterkeys ()

>>> KS

<dictionary-keyiterator Object at 0x7fe272022c00>

>>> List (KS)

[' url ', ' spam ', ' title ']



8. Pop gets the value corresponding to the key and removes it from the original dictionary.

>>> d={' x ': 1, ' Y ': 2}

>>> d.pop (' x ')

1

>>> D

{' Y ': 2}


9, Popitem random popup A set of key and value


>>> d={' title ': ' Python Web site ', ' url ': ' http://www.python.org ', ' spam ': ' 0 '}

>>> D.popitem ()

(' url ', ' http://www.python.org ')

>>> D

{' spam ': ' 0 ', ' title ': ' Python Web site '}

>>> D.popitem ()

(' spam ', ' 0 ')

>>> D

{' title ': ' Python Web site '}

>>> D.popitem ()

(' title ', ' Python Web site ')

>>> D

{}


10, SetDefault

>>> d={}

>>> d.setdefault (' name ', ' N/a ') #不指定默认值, default use None

' N/A '

>>> D

{' name ': ' N/A '}

>>> d[' name ']= ' Gumby '

>>> d.setdefault (' name ', ' N/A ')

' Gumby '

>>> D

{' name ': ' Gumby '}



11. Update the other dictionary with one dictionary, the same key will overwrite

>>> d={' title ': ' Python Web site ', ' url ': ' http://www.python.org '}

>>> x={' title ': ' Python Language Website '}

>>> d.update (x)

>>> D

{' URL ': ' http://www.python.org ', ' title ': ' Python Language Website '}



Values and Itervalues

>>> d={}

>>> d[1]=1

>>> d[2]=3

>>> d[3]=2

>>> d[4]=1

>>> d.values ()

[1, 3, 2, 1]

>>> it=d.itervalues ()

>>> it

<dictionary-valueiterator Object at 0x7fe272022c58>

>>> List (IT)

[1, 3, 2, 1]

This article from "Small Fish Blog" blog, declined reprint!

Reading notes--second edition of the basic Python tutorial--fourth dictionary: When the index is not good

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.