在我理解看来 dictinary 就是键值对 是可变的 可以增加减少键值对
>>> d={'one'=1,'two'=2}
File "<stdin>", line 1
d={'one'=1,'two'=2}
^
SyntaxError: invalid syntax
>>> d={'one'=1:'two'=2}
File "<stdin>", line 1
d={'one'=1:'two'=2}
^
SyntaxError: invalid syntax
>>> d={'one':1,'two':2}
>>> d
{'two': 2, 'one': 1}
>>> dd=dict('three'=3,'four'=4,**d)
File "<stdin>", line 1
SyntaxError: keyword can't be an expression
>>> dd=dict('three'=3,'four'=4,**d)
File "<stdin>", line 1
SyntaxError: keyword can't be an expression
>>> dd=dict(three=3,four=4,**d)
>>> dd
{'four': 4, 'one': 1, 'three': 3, 'two': 2}
dict的两种初始话方法
是否包含某个元素
>>> 'four' in dd
True
>>> 'five' in dd
False
遍历
>>> for k,v in dd.items():print(k,v)
...
four 4
one 1
three 3
two 2
get某个键值 可以如果没有的话可以返回空或者给定默认值
>>> dd.get('five',None)
>>> dd.get('five','5')
'5'
>>> dd.get('five',5)
而这样 没有该元素的话会报错
>>> dd['five']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'five'
>>> dd['one']
1
5
>>> dd.get('five')
获取某个值 并将其从dic中删除
>>> dd.pop('one')
1
>>> dd
{'four': 4, 'three': 3, 'two': 2}
若想直接删除
>>> del dd['two']
>>> dd
{'four': 4, 'three': 3}
>>>
list
>>> l=[1,2,3]
>>> l.extend(range(10)) #添加另外的list
>>> l
[1, 2, 3, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> l.insert(0,11) #指定下标添加元素
>>> l
[11, 1, 2, 3, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> l.pop(0) #得到下标元素并去除
11
>>> l.push(12)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute 'push'
>>> l.append(12) # 队尾添加一个元素
>>> l
[1, 2, 3, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 12]
>>> l.remove(12) #去除值=12的第一个元素
>>> l
[1, 2, 3, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> l.remove(1)
>>> l
[2, 3, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]