Python Create and use dictionary instances to explain _python

Source: Internet
Author: User
Tags shallow copy
The dictionary is the only built-in mapping type in Python. The values in the dictionary are not in a particular order, but are stored in a particular key.
A key can be a number, a string, or even a tuple.
1. Creating and Using dictionaries
Dictionaries can be created in the following ways:
Copy Code code as follows:

Phonebook = {' Alice ': ' 2341 ', ' Beth ': ' 9102 ', ' ceil ': ' 3258 '}

A dictionary consists of multiple keys and their corresponding values. Each key and its value are separated by a colon (:), separated by commas (,), and the entire dictionary is surrounded by a pair of curly braces. Empty dictionary: {}

1.1 Dict function
You can use the Dict function to create a dictionary through a sequence of mappings (such as other dictionaries) or (keys, values).
Copy Code code as follows:

>>> items = [(' Name ', ' Gumby '], (' age '. 42)]
>>> d = dict (items)
>>> D
{' Age ':, ' name ': ' Gumby '}
>>> d = dict (name= ' Gumby ', ' age ' =42)
>>> D
{' Age ':, ' name ': ' Gumby '}

1.2 Basic dictionary Operations
(1) Len (d) Returns the number of items (key-value pairs) in D;
(2) D[k] Returns the value associated with K;
(3) D[k]=v The value V to the key k;
(4) del d[k] Delete the key to K;
(5) K in D to check if there is a key with K in the D;

1.3 format string of the dictionary
Dictionary format string: After the% character in each conversion specifier, you can add a key (enclosed in parentheses) followed by another description element.
Any number of conversion specifiers can be obtained as long as all the given keys are found in the dictionary.
Copy Code code as follows:

>>> Temple = ' The price of the cake was $% (cake) s,the price of milk of Cake's $% (milk) s. $% (cake) s is OK "
>>> Price = {' Cake ': 4, ' Milk ': 5}
>>>print Temple% Price
' The Price's cake is $4,the price of milk of cake is $. $ is OK '

1.4 Dictionary Method
1.4.1 Clear
The clear method clears all the entries in the dictionary, which is in-situ, with no return value (or none).
Consider the following 2 types of situations:
A. Associate x with a new empty dictionary to empty it, it has no effect on y, or y is related to the original dictionary
Copy Code code as follows:

>>> x = {}
>>> y = x
>>> x[' key ' = ' value '
>>> y
{' key ': ' Value '}
>>> x = {}
>>> y
{' key ': ' Value '}

B. If you want to empty all elements in the original dictionary, you must use the Clear method.
Copy Code code as follows:

>>> x = {}
>>> y = x
>>> x[' key ' = ' value '
>>> y
{' key ': ' Value '}
>>> X.clear ()
>>> y
{}

1.4.2 Copy
The Copy method returns a new dictionary with the same key-value pair (this method implements a shallow copy because the value itself is the same, not a copy)
When you replace a value in a replica, the original dictionary is unaffected, but if you modify a value, the original dictionary changes. ]
Copy Code code as follows:

>>> x = {' A ': 1, ' B ': [2,3,4]}
>>> y = x.copy ()
>>> y[' a '] = 5
>>> y[' B '].remove (3)
>>> y
{' A ': 5, ' B ': [2,4]}
>>> x
{' A ': 1, ' B ': [2,4]}

The way to avoid this problem is to use a deep copy-deepcopy () to copy all the values that it contains.
Copy Code code as follows:

>>> x = {' A ': 1, ' B ': [2,3,4]}
>>> y = x.copy ()
>>> z = x.deepcopy ()
>>> x[' A '].append (5)
>>> y
{' A ': 1,5, ' B ': [2,3.4]}
>>> Z
{' A ': 1, ' B ': [2,3,4]}

1.4.3 Fromkeys
The Fromkeys method uses the given key to create a new dictionary, and each key defaults to a value of none, which can be raised directly in all dictionary types Dict. If you do not want to use the default value, you can also supply the value yourself.
Copy Code code as follows:

>>> {}.fromkeys ([' Name ', ' age '])
{' Age ': none, ' Name ': none}
>>>
>>> Dict.fromkeys ([' Name ', ' age '], ' unknow ')
{' Age ': ' Unknow ', ' name ': ' Unknow '}

1.4.4 get
The Get method is a more relaxed way to access a dictionary entry. When you use get to access a nonexistent key, the None value is obtained. You can also customize the default value to replace None.
Copy Code code as follows:

>>> d = {}
>>> print d.get (' name ')
None
>>> d.get ("name", ' N/A ')
' N/A '
>>> d[' name] = ' Eric '
>>> d.get (' name ')
' Eric '

1.4.5 Has_key
The Has_key method can check whether the dictionary contains the given key. D.has_key (k)
Copy Code code as follows:

>>> d = {}
>>> d.has_key (' name ')
False

1.4.6 Items and Iteritems
The items method returns all dictionary entries as a list, but there is no special order in which each item (key, value) in the list returns. The Iteritems method works roughly the same, but returns an iterator object instead of a list:
Copy Code code as follows:

>>> d = {' A ': 1, ' B ': 2, ' C ': 3}
>>>d.items
[(' A ', 1], (' B ', 2), (' C ', 3)]
>>> it = D.iteritems ()
>>> it
<dictionary-iteritems Object at 169050>
>>> List (IT)
[(' A ', 1], (' B ', 2), (' C ', 3)]

1.4.7 Keys and Iterkeys
The Keys method returns the keys in the dictionary as a list, and Iterkeys returns an iterator for the keys.

1.4.8 Pop method
The Pop method is used to obtain a value corresponding to the given key, and then remove the key-value pair from the dictionary.
Copy Code code as follows:

>>> d = {' A ': 1, ' B ': 2, ' C ': 3}
>>> D.pop (' a ')
>>> D
{' B ': 2, ' C ': 3}

1.4.10 SetDefault
The SetDefault method is similar to a GET method in that it can obtain the value associated with a given key, and set the corresponding key value without a given key in the dictionary.
Copy Code code as follows:

>>> d = {}
>>> d.setdefault (' name ', ' N/A ')
' N/A '
>>> D
{' name ': ' N/A '}
>>> d.setdefault (' name ', A)
' N/A '

As in the previous example, when the key exists, the default value (optional) is returned and the dictionary is updated accordingly, and if the key exists, it returns its corresponding value without changing the dictionary.

1.4.11 Update
The Update method can update another dictionary with one dictionary item. The provided dictionary entries are added to the old dictionary and overwritten if they have the same key.
Copy Code code as follows:

>>> d = {' A ': 1, ' B ': 2, ' C ': 3}
>>> x = {' A ': 5, ' d ': 6}
>>> d.update (x)
>>> D
{' A ': 5, ' C ': 3, ' B ': 2, ' d ': 6}

1.4.12 Values and Itervalues
The values method returns the value in the dictionary as a list (an iterator for the itervalues return value), and unlike the list of return keys, the return value list can contain duplicate elements.
Copy Code code as follows:

>>> d = {}
>>> d[1]=1
>>> d[2]=2
>>> d[3]=3
>>> d[4]=1
>>> D
{1:1, 2:2, 3:3, 4:1}
>>> d.values ()
[1, 2, 3, 1]

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.