dict and set
dict
dict
The full name dictionary is also a dictionary
>>> sx = {'沙县拌面': 7, '蒸饺': 6, '鸭腿套餐': 12}
>>> sx['沙县拌面']
7
key-value storage
key
If there is no error, it will be reported, how to avoid:
-
>>> '糖醋排骨' in sx # 用in来判断key是否存在 False
-
>>> sx.get('Thomas') #使用get()方法,key不存在的话,会返回None >>> sx.get('Thomas', -1) #或者自己指定value -1
ps. When returning
None
, the result is not displayed.
pop( )
Use pop () method to delete one key
, the corresponding one value
will also be deleted
>>> d.pop('蒸饺')
6
>>> d
{'沙县拌面': 7, '鸭腿套餐': 12}
The order in which the dict is stored has nothing to do with the order in which the keys are placed.
Space for time
dict compared to list:
dict:
- The search and insert speed is extremely fast, and will not slow down as the key increases;
- It takes a lot of memory and wastes a lot of memory.
list:
- The time to find and insert increases with the increase of elements;
- It takes up less space and wastes less memory.
dict
The key
must be immutable objects
set
set
And dict
similar, but also a set key
of collection, but not stored value
.
Because it key
can't be repeated, there set
is no repeat in the middle key
.
Create set
>>> s = set([1, 2, 3])
>>> s
{1, 2, 3}
Automatically filter duplicate elements
>>> s = set([1, 1, 2, 2, 3, 3])
>>> s
{1, 2, 3}
Add element add (key)
>>> s.add(4)
>>> s
{1, 2, 3, 4}
>>> s.add(4)
>>> s
{1, 2, 3, 4} #重复添加,并不会有效果
Remove element remove (key)
>>> s.remove(4)
>>> s
{1, 2, 3}
Set can be regarded as a collection in the mathematical sense (unordered, no repeating elements), so the two sets can do intersection and union operation:
>>> s1 = set([1, 2, 3])
>>> s2 = set([2, 3, 4])
>>> s1 & s2
{2, 3}
>>> s1 | s2
{1, 2, 3, 4}
Immutable object and mutable object understanding:
variable:
>>> a = ['c', 'b', 'a']
>>> a.sort() #对a进行排序
>>> a
['a', 'b', 'c']
Immutable:
>>> a = 'abc'
>>> a.replace('a', 'A')
'Abc'
>>> a #a并没有被改变
'abc'