Pythondict dictionary description

Source: Internet
Author: User
The dictionary is implemented by the principle of the hash table. each element is a key-value pair, and a unique hash value is calculated by the key of the element. This hash value determines the address of the element, therefore, to ensure that the element address is different, the key and the corresponding hash value of each element must be completely different, and the key type must not be modified. Therefore, the key type can be a numerical value, string constants or tuples, but not lists, because the list can be modified. The dictionary is implemented by the principle of the hash table. each element is a key-value pair, and a unique hash value is calculated by the key of the element. This hash value determines the address of the element, therefore, to ensure that the element address is different, the key and the corresponding hash value of each element must be completely different, and the key type must not be modified. Therefore, the key type can be a numerical value, string constants or tuples, but not lists, because the list can be modified.

Therefore, dictionaries have the following features:

1. the element query and insertion operations are fast, basically at the constant level.

2. the memory usage is large, and the space-to-time method is used.

Dictionary initialization

The following methods are 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'], [, 3]) # this method can also be used to combine two lists into a dictionary.

Assignment element

1. e = d # assign values by reference. e and d are always the same.

2. e = d. copy () # value assignment, which is unrelated to each other

3. d. copy () is a shallow copy. when the value of a key-value pair encounters a dictionary or list, the dictionary or list will change with the original changes, at this time, the value is equivalent to the reference or pointer of the tuples or lists, instead of itself. the tuples or lists actually point to are still original. This can be avoided by using the deepcopy () method of the copy module.

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 # add the key directly by subscript. if the key value already exists, modify the element. of course, you can also access the element.

Delete element

1. d. clear () # Delete all elements in d.

2. d. pop ('A') # Delete an element whose key value is 'A'

3. del d ['A'] # Delete an element with a key value of 'A'

Traversal element

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

Differences between items (), iteritems () and viewitems ()

Items () of python2.x is to return a list containing all the elements of dict as above. However, this is a waste of memory, so it was added later (note: the iteritems (), iterkeys (), and itervalues () functions that appear at the beginning of Python 2.2 are used to return an iterator to save memory, however, the iterator does not reflect the changes that dict has made after calling this function. Therefore, viewitems () is added, which always represents the latest element. There is only one items function in Python3.x, which is equivalent to viewitems () in 2.x.

Dictionary merge

1. dd = dict (dict1.items () + dict2.items ())

However, this efficiency is not high. through the above analysis guidance, it is actually to call items to first return the corresponding list, then execute the list addition, and then initialize the list as a dictionary.

2. dd = dict (dict1, ** dict2)

The dictionary key must be a string. In Python 2 (the interpreter is CPython), we can use a non-string as the key, but don't be fooled: this hack is only effective in Python 2 that uses the standard CPython runtime environment.

The preceding statement is equivalent

Dd = dict1.copy ()

Dd. update (dict2)

The dd. update (dict2) is equivalent

For k in dict2

Dd [k] = dict2 [k]

We can see that the update function can not only add nonexistent elements, but also modify the element values of existing keys.

It is also known that the dictionary can be merged through update and for... in.

Sort

dict = { : ,  : ,  : ,  :  sorted(dict.items(), key= sorted(dict.items(), key= d: d[1])ls = list(dict.keys())ls.sort()for k in ls:    print(k, dict[k])for k in sorted(dict.keys()):    print(k, dict[k])

The above is a detailed description of the python dict Dictionary. For more information, see other related articles in the first PHP community!

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.