Tutorial on using dict and set methods in Python

Source: Internet
Author: User
This article describes how to use the dict and set methods in Python. the dict dictionary is an important basic knowledge in Python. set is similar to it. For more information, see Dict

Python has built-in dictionaries: dict support. dict stands for dictionary and is also called map in other languages. it is stored with key-value (key-value) and has extremely fast search speed.

For example, suppose you want to find the corresponding score based on the name of the student. if you want to use list, you need two lists:

names = ['Michael', 'Bob', 'Tracy']scores = [95, 75, 85]

Given a name, to find the corresponding score, you must first find the corresponding position in names and then get the corresponding score from scores. the longer the list, the longer the time consumption.

If you use dict, you only need a "name"-"score" table to directly search for the score based on the name. no matter how large the table is, the search speed will not slow down. Write a dict in Python as follows:

>>> d = {'Michael': 95, 'Bob': 75, 'Tracy': 85}>>> d['Michael']95

Why is dict search so fast? Because the implementation principle of dict is the same as that of dictionary lookup. Assume that the dictionary contains 10 thousand Chinese characters and we want to query a word. One way is to flip the dictionary from the first page until we find the desired word, this method is used to search for elements in the list. the larger the list, the slower the query.

The second method is to first query the page number corresponding to the word in the dictionary index table (such as the first table), then directly go to the page to find the word, no matter which word to look, the search speed is very fast and will not slow down as the dictionary size increases.

Dict is the second implementation method. given a name, such as 'Michael ', dict can directly calculate the "page number" of Michael's score ", that is, the memory address stored in the 95th digit is obtained directly, so the speed is very fast.

You can guess that this key-value storage method must calculate the storage location of the value based on the key when it is put in, so that the value can be directly obtained based on the key.

To put data into dict, in addition to the initialization, you can also put the data through the key:

>>> d['Adam'] = 67>>> d['Adam']67

A key can only correspond to one value. Therefore, if a key is put into a value multiple times, the subsequent value will overwrite the previous value:

>>> d['Jack'] = 90>>> d['Jack']90>>> d['Jack'] = 88>>> d['Jack']88

If the key does not exist, dict reports the following error:

>>> d['Thomas']Traceback (most recent call last): File "
 
  ", line 1, in 
  
   KeyError: 'Thomas'
  
 

There are two methods to avoid the key nonexistent error: one is to use in to determine whether the key exists:

>>> 'Thomas' in dFalse

The second is through the get method provided by dict. if the key does not exist, you can return None or your own specified value:

>>> d.get('Thomas')>>> d.get('Thomas', -1)-1

Note: when None is returned, the interactive command line of Python does not display the result.

To delete a key, use the pop (key) method. the corresponding value is also deleted from dict:

>>> d.pop('Bob')75>>> d{'Michael': 95, 'Tracy': 85}

Note that the order in which dict is stored is irrelevant to the order in which keys are placed.

Compared with list, dict has the following features:

  • Queries and inserts are extremely fast and will not increase with the increase of keys;
  • A large amount of memory is required, resulting in a high waste of memory.

Contrary to list:

  • The time for searching and inserting increases with the increase of elements;
  • It occupies a small amount of space and wastes a small amount of memory.

Therefore, dict is a way to exchange space for time.

Dict can be used in many places that require high-speed search. it is almost everywhere in Python code. correct use of dict is very important. The first thing to remember is that the key of dict must be an immutable object.

This is because dict calculates the storage location of value based on the key. if the result of calculating the same key is different each time, dict is completely confused. The algorithm that uses the key to calculate the location is called the Hash algorithm ).

To ensure the correctness of the hash, the object as the key cannot be changed. In Python, strings, integers, and so on are immutable, so you can safely use them as keys. If the list is variable, it cannot be used as the key:

>>> key = [1, 2, 3]>>> d[key] = 'a list'Traceback (most recent call last): File "
 
  ", line 1, in 
  
   TypeError: unhashable type: 'list'
  
 

Set

Similar to dict, set is also a set of keys, but does not store values. Because keys cannot be repeated, there are no duplicate keys in the set.

To create a set, you must provide a list as the input set:

>>> s = set([1, 2, 3])>>> sset([1, 2, 3])

Note that the input parameter [1, 2, 3] is a list, and the displayed set ([1, 2, 3]) only tells you that the set contains 1, 2, 3, 3. the displayed [] element does not indicate a list.

Repeated elements are automatically filtered in the set:

>>> s = set([1, 1, 2, 2, 3, 3])>>> sset([1, 2, 3])

The add (key) method can be used to add elements to the set. you can add them again, but it does not work:

>>> s.add(4)>>> sset([1, 2, 3, 4])>>> s.add(4)>>> sset([1, 2, 3, 4])

You can use the remove (key) method to delete elements:

>>> s.remove(4)>>> sset([1, 2, 3])

Set can be regarded as a set of unordered and non-repeating elements in the mathematical sense. Therefore, the two sets can perform operations such as intersection and union in the mathematical sense:

>>> s1 = set([1, 2, 3])>>> s2 = set([2, 3, 4])>>> s1 & s2set([2, 3])>>> s1 | s2set([1, 2, 3, 4])

The only difference between set and dict is that the corresponding value is not stored. However, the principle of set is the same as that of dict. Therefore, it cannot be placed into a variable object, because it is impossible to determine whether two mutable objects are equal, it is impossible to ensure that "there will be no repeated elements" in the set ". Put list in set to see if an error is reported.
Discuss immutable objects

As we have mentioned above, str is a constant object, while list is a variable object.

For a variable object, such as list, to operate on the list, the content inside the list will change, for example:

>>> a = ['c', 'b', 'a']>>> a.sort()>>> a['a', 'b', 'c']

For immutable objects, such as str, do the following operations on str:

>>> a = 'abc'>>> a.replace('a', 'A')'Abc'>>> a'abc'

Although the string has a replace () method, it does change to 'ABC', but variable a is still 'ABC' at last, how should we understand it?

Let's change the code to the following:

>>> a = 'abc'>>> b = a.replace('a', 'A')>>> b'Abc'>>> a'abc'

Always remember that a is a variable, while 'ABC' is a string object! Sometimes, we often say that the content of object a is 'ABC', but it actually means that object a is a variable and the content of object it points to is 'ABC ':

When we call. replace ('A', 'A') is actually called on the string object 'ABC'. Although this method is called replace, but the content of the string 'ABC' is not changed. On the contrary, the replace method creates a new string 'ABC' and returns it. if we use variable B to point to the new string, it is easy to understand, variable a still points to the original string 'ABC', but variable B points to the new string 'ABC:

Therefore, for a constant object, calling any method of the object itself does not change the content of the object itself. On the contrary, these methods create new objects and return them. in this way, immutable objects are always immutable.
Summary

Dict using the key-value storage structure is very useful in Python. it is important to select an immutable object as the key. The most common key is the string.

Although tuple is a constant object, try to put (1, 2, 3) and (1, [2, 3]) into dict or set and explain the result.

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.