Dict
#!/usr/bin/env python3#-*-coding:utf-8-*-#dict >>> d = {' Michael ': Up, ' Bob ': $, ' Tracy ': 85}>>> d[' Michael ']95>>> d[' adam ' = 67>>> d[' adam ']67>>> d[' jack '] = 90>>> d[' Jack ']90> >> d[' jack ' = 88>>> d[' Jack ']88>>> d[' Thomas ']traceback (most recent call last): File "< Stdin> ", line 1, in <module>keyerror: ' Thomas ' >>> ' Thomas ' in Dfalse>>> d.get (' Thomas ') # return here None, the command interaction line will not display >>> d.get (' Thomas ',-1) #返回子集指定的value -1>>> d.pop (' Bob ') #pop (key) method, the corresponding value will be deleted 75 >>> d{' Jack ': A, ' Tracy ': ' Michael ': +, ' Adam ': 67}
The order in which the dict is stored inside is not related to the order in which the key is placed
Compared with list, Dict has the following features:
1. The search and insertion speed is very fast, will not increase along with the increase of key
2. Need to occupy a lot of memory, memory waste more
And the list is the opposite:
1. The time to find and insert increases as the element increases;
2. Small footprint, very 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.
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, if each calculation
The same key results in a different result, and the dict inside is completely chaotic. This through key
The algorithm for calculating the location is the hashing 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.
The list is mutable and cannot be a key.
>>> key = [1, 2, 3]>>> d[key] = ' A list ' Traceback (most recent call last): File "<stdin>", Lin E 1, in <module>typeerror:unhashable type: ' List '
Set
#!/usr/bin/env python3#-*-coding:utf-8-*-#创建set需要提供一个list作为输入集合 >>> s = set ([1, 2, 3]) >>> s{1, 2, 3}& gt;>> s = Set ([1, 1, 2, 2, 3, 3]) #重复元素在set中自动被过滤 >>> s{1, 2, 3}>>> S.add (4) #添加元素 >>> s{1, 2, 3, 4}>>> S.add (4) #添加重复元素, no effect >>> s{1, 2, 3, 4}>>> s.remove (4) #删除元素 >>> s{1, 2, 3 }>>> S1 = set ([1, 2, 3]) >>> s2 = Set ([2, 3, 4]) >>> S1 & S2 #交集 {2, 3}>>> S1 | S2 #并集 {1, 2, 3, 4} #再谈不可变对象 >>> a = [' C ', ' B ', ' A ']>>> a.sort () >>> a[' A ', ' B ', ' C ']>>> a = ' abc ' >>> b = a.replace (' A ', ' a ') #这里虽然对a进行操作 # but actually produced a new string and let B point to the new string >>> B ' abc ' >>> a ' abc '
For non-mutable objects, any method that invokes the object itself does not alter the contents of the object itself, but instead, these methods create new objects and return them, guaranteeing that immutable itself is immutable forever.
Python Learning notes-dict and set