Python dict Dictionary detailed description

Source: Internet
Author: User
The dictionary is implemented by the principle of the hash table, each element is a key value pair, through the element's key to calculate a unique hash value, the hash value determines the address of the element, so in order to ensure that the element address is not the same, you must ensure that the key of each element and the corresponding hash value is completely different, And the type of the key must be non-modifiable, so the type of the key can make a numeric value, a string constant or a tuple, but not a list, because the list can be modified.

Therefore, the dictionary has the following characteristics:

1, the element query and insert operation is very fast, basically is the constant level

2, occupy a large memory, the use of space to change the time method

Initialization of the Dictionary

The following methods are all equivalent

D={' A ': 1, ' B ': 2, ' C ': 3}

D=dict ({' A ': 1, ' B ': 2, ' C ': 3})

D = dict (' A ', 1), (' B ', 2), (' C ', 3)])

D = dict (A=1, b=2, c=3)

D = dict (Zip ([' A ', ' B ', ' C '], [[+]]) #这个方法也可以用作将两个列表合并成一个字典

Assignment element

1, E = d# reference assignment, E, D is always the same

2, E = D.copy () #值赋值, there is no correlation between the two

3, D.copy () is a shallow copy, when the value of a key pair is encountered in a dictionary or list, the dictionary or list also changes as the original changes, the value is equivalent to a tuple or list of references or pointers, rather than itself, to the tuple or list is actually the original. Use the Deepcopy () method of the Copy module to avoid this situation.

Import Copydict1 = {' A ': [1, 2], ' B ': 3}dict2 = Dict1dict3 = Dict1.copy () Dict4 = Copy.deepcopy (dict1) dict1[' b '] = ' change ' dict1[' A '].append (' change ') print Dict1  # {' A ': [1, 2, ' Change '], ' B ': ' Change '}print dict2  # {' A ': [1, 2, ' Change ' ], ' B ': ' Change '}print dict3  # {' A ': [1, 2, ' Change '], ' B ': 3}print dict4  # {' A ': [1, 2], ' B ': 3}

add element

1, d[' d '] = 4# directly by subscript Add, if the key value already exists, that is to modify the element, of course, can also access the element

Delete Element

1, d.clear () #删除d中的所有元素

2, D.pop (' a ') #删除键值为 ' a ' elements

3, Del d[' a '] #删除键值为 ' a ' element

Traversing elements

For K in D:

print ' d[%s]= '% k,d[k]

Or

For k,v in D.items ():

print ' d[%s]= '% k,v

Or

For k,v in D.iteritems ():

print ' d[%s]= '% k,v

Or

For k,v in D.viewitems ():

print ' d[%s]= '% k,v

Items (), Iteritems () and viewitems () differences

Python2.x's items () is a list that contains all the elements of dict, like the one above, but because of this too much memory, it was later added (note: The beginning of Python 2.2) Iteritems (), Iterkeys (), Itervalues () is a set of functions that return a iterator to save memory, but the iterator does not reflect the changes that dict after the function was called. So Viewitems () is added and always represents the newest element. There is only one items function in python3.x, and this function is equivalent to Viewitems () in 2.x.

Dictionary Merging

1, DD = Dict (Dict1.items () + dict2.items ())

But this is not very efficient, through the above analysis, it is actually called items to return the corresponding list, and then perform the list to add, and then initialize the list to a dictionary as the form of initialization

2, DD = Dict (Dict1, **dict2)

The key of the dictionary must be a string. In Python 2 (The Interpreter is CPython), we can use a non-string as a key, but don't be deceived: this hack just happens to be valid in Python 2, which uses the standard CPython runtime environment.

The above statement is equivalent to

dd = Dict1.copy ()

Dd.update (DICT2)

The Dd.update (DICT2) is also equivalent to

For K in Dict2

DD[K] = Dict2[k]

It is known that the function of update can not only add non-existent elements, but also modify the element values of existing keys.

And through the above know through update and for...in can also be merged dictionary.

Sort

Dict = {:,  :,  :,  :  sorted (Dict.items (), key= sorted (Dict.items (), key= d:d[1]) ls = list (Dict.keys ()) L S.sort () for k in LS:    print (k, dict[k]) for K in Sorted (Dict.keys ()):    print (k, dict[k])
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.