Python Dictionary method

Source: Internet
Author: User
Tags shallow copy

This article is referenced from the basic Python Tutorial (second edition)

Operation Grammar Example Results
Build a dictionary

Dict ()

1. Creating a dictionary with keyword parameters

2. Building a dictionary with other mappings as parameters

1.d = Dict (name= ' Gumby ', age=42)

D

2.items = [(' Name ', ' Gumby '), (' Age ', 42)]

D = dict (items)

D

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

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

Fromkeys ()

1. Create a new dictionary for the specified key

2. Call Fromkeys with Dict

3. If you do not want to use none as the default value, you can provide the default value yourself

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

2.dict.fromkeys ([' Name ', ' age '])

3.dict.fromkeys ([' Name ', ' age '], ' (unknown) ')

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

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

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

Clear Dictionary

Clear ()

1. Clear all items in the dictionary

2. No return value (or the return value is None)

1.d = {' name ': ' Gumby ', ' Age ': 42}

Value = D.clear ()

D

2. Print value

{}

None

Shallow copy

Copy ()

1. Returns a new dictionary with the same key-value pair

2. The original dictionary is not affected when a value is substituted in the replica

3. When you modify a value (not a replacement) in a replica The original dictionary will change

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

y = x.copy ()

y

 

2.y[' username '] = ' mhl '

y

x

 

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

Y

x

 

 

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

& nbsp;

{' username ': ' MHL ', ' Machines ': [' foo ', ' Bar ', ' Baz '}

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

 

 

{' username ': ' MHL ', ' Machines ': [' foo ', ' Baz '}}

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

Deep copy

Deepcopy ()

1. The original dictionary is unaffected when a value is modified (not replaced) in the replica

From copy import deepcopy

D = {' names ': [' Alfred ', ' Bertrand '}

Deep = deepcopy (d)

deep[' names '].append (' Clive ')

Deep

D

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

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

accessing dictionary items/setting default values

Get ()

1. More relaxed access to the dictionary entry, access to a nonexistent key, no error

2. Customizing default values

1.d = {}

Print d.get (' name ')

2.d.get (' name ', ' N/A ')

None

' N/A '

SetDefault ()

1. More relaxed access to the dictionary entry, access to a nonexistent key, no error

2. Customizing default values

3. When the key is present, return the corresponding value

1.d = {}

Print D.setdefault (' name ')

2.D = {}

D.setdefault (' name ', ' N/A ')

3.d = {' name ': ' Gumby '}

D.setdefault (' name ', ' N/A ')

None

' N/A '

' Gumby '

Check key

Has_key ()

1.d.has_key (key) equivalent to K in D

D = {}

D.has_key (' name ')

d[' name '] = ' Eric '

D.has_key (' name ')

False

True

Iteration

Iteration of keys: Keys () and Iterkeys ()

1.keys () returns the keys in the dictionary as a list

2.iterkeys () The iterator that returns the key

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

D.keys ()

2.ik = D.iterkeys ()

Ik

List (IK)

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

<dictionary-keyiterator Object at 0x0000000002c1fa98>

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

Iterations of Values: Values () and itervalues ()

1.values () returns the values in the dictionary as a list

2.itervalues () iterator that returns a value

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

D.values ()

2.IV = D.itervalues ()

iv

List (iv)

[' http://www.python.org ', 0, ' python Web Site ']

<dictionary-valueiterator Object at 0x0000000002c1fae8>

[' http://www.python.org ', 0, ' python Web Site ']

Iteration of key-value pairs: items () and Iteritems ()

1.items () returns all dictionary entries as a list

2.iteritems () returns an iterator for all dictionary items

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

D.items ()

2.it = D.iteritems ()

It

List (IT)

[(' url ', ' http://www.python.org '), (' spam ', 0), (' title ', ' Python Web Site ')]

<dictionary-itemiterator Object at 0x0000000002c1fb38>

[(' url ', ' http://www.python.org '), (' spam ', 0), (' title ', ' Python Web Site ')]

Removed from

Pop ()

1. Get the value of the given key and remove the key-value pair from the dictionary

D = {' X ': 1, ' Y ': 2|

D.pop (' x ')

D

1

{' Y ': 2}

Popitem ()

1. Remove random items

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

D.popitem ()

D

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

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

Update

Update ()

1. Update another dictionary with one dictionary item

D = {' title ': ' Python Web Site ', ' url ': ' http://www.python.org ', ' changed ': ' Mar 22:09:15 MET 2008 '}

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

D.update (x)

D

{' URL ': ' http://www.python.org ', ' changed ': ' Mar 22:09:15 MET ', ' title ': ' Python Language Website '}

Python Dictionary method

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.