Python basics-dictionary)

Source: Internet
Author: User
Tags hashable

The dictionary dict is the only standard mapping type in Python and is also embedded in the Python interpreter.

Mapping object maps a hashable value to any object.

What is hash?

An object is hashable, which means that the object has a constant hash value (hash value) during its lifetime, that is, _ hash __() value returned by the method.

All immutable built-in objects are hashable, such as string and tuple. All mutable built-in containers are not hashable, such as list and dict (that is, there is no _ hash _ () method ). All custom use-defined class objects are hashable and can only be equal to themselves. The hashvalue is the value of its id (object, here, id () is a built-in function. The address of the object in the memory is obtained when CPython is implemented.

The keys of the Dictionary must be Hash-able. Therefore, tuple and string can be used as keys, while list cannot be used as keys. I will explain this in detail later, or refer to the 3rd articles at the end of this article.

Dict itself is a class

Class dict (mapping)

1. Create a dictionary

? 1
2
3
4
5
6 >>> d = dict ({1: 'A', 2: 'B', 3: 'C'}) # built using the dict class
>>> D
{1: 'A', 2: 'B', 3: 'C '}
>>> D2 = {1: 'A', 2: 'B', 3: 'C'} # Build directly. Note the syntax, braces, colons, and commas.
>>> D2
{1: 'A', 2: 'B', 3: 'C '}
 

2. operations supported by dictionary

As the only standard mapping type in Python, dictionary supports addition, deletion, query, and overall update operations.

Some operations are implemented by dict member functions, some operations are implemented by Python's built-in functions (built-in), and Python's del statements are also used.

2.1 reference Element

Directly use d [key] to obtain the object corresponding to the key, but if the key does not exist, if the standard dict is used, a KeyError exception will be thrown. However, if we have derived a dictionary from dict, we only need to define the _ missing _ function. If the key does not exist, this function will be called with the key as the parameter, let's test it.

Write a module, mdict. py


1 class myDict (dict ):
2 def _ missing _ (self, key ):
3 print "_ missing _ called, key =", key4 return "^_^" then open the Python command line interpreter and import mdict


>>> From mdict import myDict
>>> D = myDict ({1: 'A', 2: 'B', 3: 'C '})
>>> D
{1: 'A', 2: 'B', 3: 'C '}
>>> D [1]
'A'
>>> D [4]
_ Missing _ called, key = 4 then _^ You Can See That _ missing _ () is called.

If you only want to get the value corresponding to a key and do not want to change it, use the class method get (), which is similar to the concept of "Reference" and "value" in C ++.


>>> A = d. get (1)
>>>
'A'

2.2 operations implemented by class methods

>>> D. clear () # clear

>>> D. copy () # copy to generate another, shallow copy)

D. keys (), d. values (), d. items ()

All three generate the copy of keys, values, and items corresponding to the dictionary. The returned results are all list, and d. items () generate the list of (key, value) binary tuple.


>>> D. items ()
[(1, 'A'), (2, 'B'), (3, 'C')]
>>> D. keys ()
[1, 2, 3]
>>> D. values ()
['A', 'B', 'C'] d. viewkeys (), d. viewvalues (), d. viewitems ()

All three generate the view object corresponding to the dictionary. The view object is a dynamic reflection of the (key, value) in the dictionary. When the content in the dictionary changes, the view object also changes.


>>> Viewkeys = d. viewkeys ()
>>> Viewkeys
Dict_keys ([1, 2, 3])
>>> List (viewkeys)
[1, 2, 3]
>>> Del d [1]
>>> List (viewkeys)
[2, 3]

 

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.