Python Learning day Seventh-Dict and set

Source: Internet
Author: User
Tags stdin

Today we mainly learn about Python's dict (full name dictionary) and set. The usage of dict is similar to the map table in JavaScript, the key + value structure language. and set, exactly, is just a collection of keys.

Dict

Direct Sticker Code

>>> d = {'zhangsan'lixi'wuliu ': '>>> d['zhangsan']95

Dict Insertion

>>>d['wangba'= 90//Direct insert Wangba The student's score, print again d>>>d{' Lixi ' ' Wangba ' ' Zhangsan ' ' Wuliu ': 76}

Ps:dict is an unordered collection, the above example, where you insert a record, but the order in which it is printed is unordered.

Learning JavaScript knows that a key in a map can only correspond to a unique value, so, multiple times a key is placed in value, and the value below will flush the previous value:

>>> d['wangba'] = 88>>> d['wangba'] 88>>> d['wangba'] = 66>>> d['wangba'  ]66

If key does not exist, Dict will get an error:

>>> d['liuhai']traceback (most recent):  "  <stdin>" in <module>'C'

To avoid a key that does not exist, there are two ways to in determine whether a key exists:

>>>'liuhai' in dfalse

The second is the Get method provided by Dict, if key does not exist, you can return none, or the value you specified:

>>> d.get ('liuhai')// null, does not show results >>> d.get (' Liuhai ',-1)-1

Note: When you return None , the interactive command line of Python does not display the results.

Key Delete

To delete a key, the pop(key) corresponding value is also removed from the dict using the method:

>>> d.pop ('wangba')90>>> d{'Lixi  'zhangsan'wuliu': 76}

Again, the order of Dict internal storage is not related to the order in which key is placed, it is an unordered collection.

Compared with list, Dict has the following features:

    1. The speed of finding and inserting is very fast and will not slow with the increase of key;
    2. It takes a lot of memory, and it wastes a lot of memory.

And the list is the opposite:

    1. The time to find and insert increases as the element increases;
    2. Small footprint and little wasted memory.

So,Dict is a way of exchanging space for time .

Dict can be used in many places where high-speed lookups are needed, almost everywhere in Python code, it is important to use dict correctly, and the first thing to keep in mind is that the Dict key must be an immutable object .

This is because Dict calculates the storage location of value based on key, and if each calculation of the same key results in a different result, the dict interior is completely chaotic. The algorithm for calculating the position by key is called the hash Algorithm (hash).

To ensure the correctness of the hash, the object as a key can not be changed. In Python, strings, integers , and so on are immutable, so you can safely use them as keys. The List is mutable and cannot be a key:

>>> key = [1, 2, 3]'a list'Traceback (most recent call last):   " <stdin> "  in <module>'list'
Set

The set is relative to Dict, which stores only key and does not store value.

Direct Sticker Code:

>>>s = Set ([>>>set])>>>s([[+])

Set Insert key:

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

If set inserts a duplicate key:

>>> S.add (2)//key Duplicate will be processed, cannot appear duplicate key>>> sset ([1, 2, 3, 4])

Set to remove key:

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

Ps:set features are similar to Dict, are unordered collections, keys are immutable, and the list cannot be a key.

Above, we've been keeping python integers and strings pointing to immutable content. What is content not mutable? Take a look at the following example, excerpt from the Internet:

' ABC ' >>> a.replace ('a'a')'  ABC' >>> a'abc'

Although the string has a replace() method, it does change ‘Abc‘ , but the variable is a still at the end ‘abc‘ , how should it be understood?

Let's start by changing the code to the following:

' ABC '>>> b = a.replace ('a'a')> >> b'abc'>>> a'ABC '

Always keep in mind that a it is a variable, but a ‘abc‘ string Object! Sometimes, we often say that the object's a content is ‘abc‘ , but actually refers to, a itself is a variable, it points to the content of the object is ‘abc‘ :

When we call a.replace(‘a‘, ‘A‘) , the actual invocation method replace is on the string object ‘abc‘ , and although the method is called, it replace does not change ‘abc‘ the contents of the string. Instead, the replace method creates a new string ‘Abc‘ and returns, and if we point to the new string with a variable, b it's easy to understand that the variable a still points to the original string ‘abc‘ , but the variable points to the b new string ‘Abc‘ :

Therefore, Python does not change the contents of the object itself by invoking any of its own methods for immutable objects. Instead, these methods create a new object and return it.

In this way, the immutable object itself is guaranteed to be immutable forever.

Python Learning day Seventh-Dict and set

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.