Python creating and using a dictionary instance

Source: Internet
Author: User
The dictionary is the only built-in mapping type in Python. The values in the dictionary are not in a special order, but are stored in a specific 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 CodeThe code is 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 (:), and the items are separated by commas (,), and the entire dictionary is enclosed by a pair of curly braces. Empty dictionary: {}

1.1 Dict function
You can use the Dict function to build a dictionary from a sequence of mappings (such as other dictionaries) or (keys, values).
Copy CodeThe code is 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 in D (key-value pairs);
(2) D[k] Returns the value associated to K;
(3) The D[k]=v associates the value V to the key k;
(4) del d[k] Delete the key to K;
(5) K in D check if there is a key to K in D;

1.3 Formatting strings for dictionaries
Dictionary format string: After the% character in each conversion specifier, you can add (in parentheses) the key, followed by the other explanatory elements.
Any number of conversion specifiers can be obtained as long as all the given keys can be found in the dictionary.
Copy CodeThe code is as follows:


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


1.4 Dictionary Methods
1.4.1 Clear
The clear method clears all the entries in the dictionary, which is an in-place operation, with no return value (or none returned).
Consider the following 2 scenarios:
A. Associate x with a new empty dictionary to empty it, which has no effect on y, and y is associated to the original dictionary
Copy CodeThe code is as follows:


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


B. If you want to empty all the elements in the original dictionary, you must use the Clear method.
Copy CodeThe code is 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 pairs (this method implements a shallow copy because the value itself is the same, not the copy)
When you replace a value in a copy, the original dictionary is unaffected, but if a value is modified, the original dictionary changes. ]
Copy CodeThe code is 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 of-deepcopy () and copy it to include all the values.
Copy CodeThe code is 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 type Dict. If you do not want to use the default values, you can also provide your own values.
Copy CodeThe code is 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, you get a value of none. You can also customize the default value to replace None.
Copy CodeThe code is 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 CodeThe code is 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 each item (key, value) in the list is returned with no special order. The Iteritems method works roughly the same, but returns an iterator object instead of a list:
Copy CodeThe code is as follows:


>>> d = {' A ': 1, ' B ': 2, ' C ': 3}
>>>d.items
[(' A ', 1), (' B ', 2), (' C ', 3)]
>>> it = D.iteritems ()
>>> it

>>> 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 key.

1.4.8 Pop method
The Pop method is used to get the value corresponding to the given key, and then the key-value pair is removed from the dictionary.
Copy CodeThe code is 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 somewhat similar to the Get method, which is the ability to obtain a value associated with a given key, and to set the corresponding key value in the case where the dictionary does not contain a given key.
Copy CodeThe code is as follows:


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


As in the example above, when the key is present, the default value is returned (optional) and the dictionary is updated accordingly, and if the key exists, it returns its corresponding value, but does not change 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 the same key is used.
Copy CodeThe code is 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 that itervalues the return value), which, unlike the list of returned keys, can contain duplicate elements in the return value list.
Copy CodeThe code is 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.