The Python dictionary is a detailed one (basic usage)

Source: Internet
Author: User
Tags iterable shallow copy

Python dictionary is a very important base type in Python, it is an efficient base type, not only used in writing programs, but even the implementation of Python's low-level use of a large number of dictionaries.

Learn Python dictionaries mainly from a few aspects

1. Basic use of Dictionaries
2. The extension of the dictionary and some of its class libraries (for special-purpose dictionaries)
3. Customize your own dictionary
4. The bottom implementation of the dictionary
the basic use of a dictionary Create a dictionary

There are many ways to create a dictionary, however, it is important to note that the dictionary key must be hashed, so the hash value of the dictionary's key should not change in the object's lifecycle, including immutable types such as: str, bytes, int, and frozen set, And a tuple that does not contain mutable type items, and an object that implements the same hash value of the eq() and hash() methods.

The following is a list of some ways to construct a dictionary
(Only consider the method, do not pay attention to efficiency issues, on efficiency issues after in-depth study to analyze)

How to construct a dictionary directly

A = {' One ': 1, ' two ': 2, ' Three ': 3}

Create a dictionary from the factory method

To construct dictionaries by means of dictionary parameters:

b = Dict (one=1, two=2, three=3)

Using the Zip method to construct

c = dict (Zip ([' One ', ' two ', ' three '], [1, 2, 3])

How tuples are on the list

D = dict ([(' Two ', 2), (' One ', 1), (' Three ', 3)]

Directly in the form of a dictionary as a structural parameter

E = Dict ({' Three ': 3, ' one ': 1, ' two ': 2})

How the list is set to tuples

f = dict ([' One ', 1], [' Two ', 2],[' three ', 3])

Fromkeys Create a default value dictionary:

g = Dict.fromkeys ([' One ', ' tow ', ' three '], 1)

Dictionary derivation type

H = {value:index+1 for index, value in  enumerate ([' One ', ' tow ', ' Three ']}

See the dictionary in Python is very powerful, it is very rich and convenient to operate, the following listed some common operations common operations

What are the methods used in the dictionary?
First look at the Dictionary class diagram

Dict_test = {1: ' One ', 2: ' Two ', 3: ' Three '} container
You can use in to determine whether an element exists:

>>> 1 in Dict_test           

True Mapping

>>> Dict_test.keys ()
Dict_keys ([1, 2, 3])
>>> dict_test.values ()
dict_values ([' One ', ' Two ', ' three ']
>>> dict_test.items () dict_items ((
1, ' one '), (2, ' two '), (3, ' three ')]

Note: In Python3, all three methods return the view, and the key can be used to get the value

>>> Dict_test[1]

' One ' can also directly match the key to the value

>>> dict_test[4] = ' Four '

>>> dict_test

{1: ' One ', 2: ' Two ', 3: ' Three ', 4: ' Four '} and using the Get method to obtain the value, if no this key returns the default value

>>> dict_test.get (1, ' 1 ')

' One '

>>> dict_test.get (' 1 ', ' 1 ')

' 1 ' sized
Get the length of a dictionary

>>> Len (dict_test)

3 iterable
Can iterate and be iterated objects (traversed by key)

>>> for value in Dict_test:
...     Print (value) ...

1
2
3

>>> from collections import iterable
>>> isinstance (dict_test, iterable)

True

>>> ITER (Dict_test)

Iterator
becomes an iterator

>>> iter_test = iter (dict_test)
>>> Next (iter_test)

1

>>> Next (Iter_test)

2

>>> Next (Iter_test)

3

>>> Next (Iter_test)

Traceback (most recent call last):
File "", Line 1, in
Stopiteration some other methods

>>> dir (dict_test)
[' __class__ ', ' __contains__ ', ' __delattr__ ', ' __delitem__ ', ' __dir__ ', ' __doc__ ', ' __eq__ ', ' __format__ ', ' __ge__ ', ' __ getattribute__ ', ' __getitem__ ', ' __gt__ ', ' __hash__
', ' __init__ ', ' __iter__ ', ' __le__ ', ' __len__ ', ' __lt__ ', ' __ne __ ', ' __new__ ', ' __reduce__ ', ' __reduce_ex__ ', ' __repr__ ', ' __setattr__ ', ' __setitem__ ', ' __sizeof__ ', ' __s
tr__ ', ' __subclasshook__ ', ' clear ', ' copy ', ' Fromkeys ', ' get ', ' items ', ' Keys ', ' pops ', ' popitem ', ' setdefault ', ' Update ', ' value S ']
The usual method
The pop removes and returns the value of the removed key, which requires a key argument
>>> Dict_test.pop (1)

' One '

>>> Dict_test

{2: ' Two ', 3: ' Three '}

Ditto, Popitem removes and returns the removed key value pair

>>> Dict_test.popitem ()

(2, ' two ')

>>> Dict_test

{3: ' three '}

The SetDefault method is similar to a GET method, except that if the key is not found, the value of the key is set to the default value, and the value is returned and, if there is a key, the value of the key is returned directly.

>>> Dict_test.setdefault (4, ' four ')

' Four '

>>> Dict_test

{1: ' One ', 2: ' Two ', 3: ' Three ', 4: ' Four '}

Delete the key value pairs in the dictionary directly

>>> del dict_test[1]
>>> dict_test

{2: ' Two ', 3: ' Three ', 4: ' Four '}

copy method, directly invoke copy () as a shallow copy, that is, a new object is created, but the content is actually a reference to the contents of the original object, see the following example

>>> dict_test =  {' One ': 1, ' two ': [1,1]}
>>> dict_copy = dict_test.copy ()
>>> dict_copy[' two '].append (1)
>>> dict_test[' two ']

[1, 1, 1]

There's no problem with deep copy.

Dict_test =  {' One ': 1, ' two ': [1,1]}
import copy
dict_deep_copy = copy.deepcopy (dict_test)
dict_deep_copy[' two '].append (1)
dict_test[' two ']

[1, 1]

Some of the methods have already been demonstrated before, and this is no longer to say that update is used for dictionary merging, there are many ways to merge, and frequently used, merging and updating dictionaries

Here are some ways to:

Dict1 = Dict ([(1, ' One '), (2, ' two ')])
Dict2 = {2: ' Two_two ', 3: ' Three '}

use the Update method directly (this will change the dictionary)

>>> dict1.update (dict2)
>>> Dict1

{1: ' One ', 2: ' Two_two ', 3: ' Three '}

You can use the Copy method or the factory method to create a new dictionary without changing the original dictionary

>>> dict1_copy = dict1.copy () # dict (dict1)
>>> dict1_copy.update (dict2)
>>> Dict1 _copy

{1: ' One ', 2: ' Two_two ', 3: ' Three '}

>>> Dict1

{1: ' One ', 2: ' Two '}

There are some problems with the way in which you can combine the uncoupling, as follows:

>>> dict (Dict1, **dict2)

Traceback (most recent call last):
File "", Line 1, in
Typeerror:keyword arguments must be strings

so this approach only fits the case where key is a variable name

Dictionary merging can also be done using a dictionary-derived method

>>> {key:value for D in [Dict1, Dict2] for key, value in D.items ()}

{1: ' One ', 2: ' Two_two ', 3: ' Three '}

The method of adding all the loops, similar to the previous derivation

>>> dict (List (Dict1.items ()) + list (Dict2.items ()))

{1: ' One ', 2: ' Two_two ', 3: ' Three '}

Using the connection operator ' | '

>>> Dict (Dict1.items () | Dict2.items ())

{1: ' One ', 2: ' Two ', 3: ' Three '}

>>> Dict (Dict2.items () |dict1.items ())

{1: ' One ', 2: ' Two_two ', 3: ' Three '}

the order of coverage here is changed, and if duplicate key is used as the value of the key in the first dictionary as the final merged value

With the help of other class libraries

>>> from itertools import chain                                                                                                                                           
>>> dict (Chain (Dict1.items (), Dict2.items ())

{1: ' One ', 2: ' Two_two ', 3: ' Three '}

>>> from collections import Chainmap
>>> chainmap ({}, Dict2, Dict1)

Chainmap ({}, {1: ' One ', 2: ' Two '}, {2: ' Two_two ', 3: ' Three '})

>>> Dict (Chainmap ({}, Dict1, Dict2))

{1: ' One ', 2: ' Two ', 3: ' Three '}
The first empty dictionary here is to not change the values in the Dict1, but note the order of the dictionary emissions, Dict1 need to be put in the end, because we need the value in Dict2 to overwrite the value in Dict1, which does not go through the dictionary because it first generates a view, In the search will not be matched, Chainmap will not be directly into dict, the need to dict factory methods for conversion, which is suitable for merging multiple dictionaries

Dict3 = {3: ' Three_three ', 4: ' Four '}
>>> Dict (Chainmap ({}, Dict3, Dict2, Dict1))

{1: ' One ', 2: ' Two_two ', 3: ' Three_three ', 4: ' Four '}

Note the position of the dictionary in the parameter, need to update the dictionary to put the last

All the way to python3.5 (this convenient and quick way is only valid in the above)

>>> {**dict1, **dict2}

{1: ' One ', 2: ' Two_two ', 3: ' Three '}

In addition to merging the size of the two dictionaries is also used to compare dictionaries

since there is a richer comparison character added after python2.1, the Python2 retains the CMP built-in function, so it can be compared directly to the CMP method but the built-in method is removed in Python3. You need to implement the corresponding methods of the comparison, such as < corresponding to _lt_, other similar: <= _le_, = = _eq_,!= _ne_, > _gt_, >= _ge_.

The comparison order of dictionaries, the following rules are observed in Python2
First compare the length of the dictionary, then compare the dictionary's key, and finally compare the dictionary's value

And in Python3, you need to implement those comparison methods.

Dict1 = {1: ' One ', 3: ' Three '}
Dict2 = {2: ' Two ', 3: ' Three_three '}
Condition = True if Dict1 >= dict2 else False
condition
---------------------------------------------------------------------------

typeerror                                 traceback (most Recent call last)

<ipython-input-26-6e55c3e20291> in <module> ()
----> 1 condition = True if Dict1 >= dict2 Else False
      2 condition


typeerror:unorderable types:dict () >= dict ()
dict1.__lt__ (DICT2)
notimplemented

The other thing to say is that the keys in the dictionary are unordered collections, so you can use some of the operations of the collection to process the dictionary, such as finding the key-value pairs that are not in the first dictionary, and you can do this by using the difference complement of the set

{Key:dict1[key] for key in set (Dict1)-Set (DICT2)}

{1: ' One '}

There are other dictionary operations, such as sorting dictionaries, expanding and transforming their own dictionary types, and so on, the next time to summarize.

These examples above are tested under python3.4.3.

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.