字典类型内置方法
优先掌握(*****)
- 按key存取值:可存可取
- 长度len
- 成员运算in和not in
- 删除del
- 键keys()、值values()、键值对items()
- 循环
1.按key存取值:可存可取
# dic之按key存取值
dic = {'a': 1, 'b': 2}
print(f"first dic['a']: {dic['a']}")
dic['a'] = 3
print(f"second dic['a']: {dic['a']}")
first dic['a']: 1
second dic['a']: 3
2.长度len
# dic之长度len
dic = {'a': 1, 'b': 2}
print(f"len(dic): {len(dic)}")
len(dic): 2
3.成员运算in和not in
# dic之成员运算in和not in
dic = {'a': 1, 'b': 2}
print(f"'a' in dic: {'a' in dic}")
print(f"1 in dic: {1 in dic}")
'a' in dic: True
1 in dic: False
4.删除
# dic之删除del
dic = {'a': 1, 'b': 2}
del dic['a']
print(f"dic.get('a'): {dic.get('a')}")
dic.get('a'): None
# dic之删除pop()
dic = {'a': 1, 'b': 2}
dic.pop('a') # 指定元素删除
print(f"dic.pop('b'): {dic.pop('b')}")
print(f"dic.get('a'): {dic.get('a')}")
dic.pop('b'): 2
dic.get('a'): None
# dic之删除popitem()
dic = {'a': 1, 'b': 2}
print(f"dic.popitem(): {dic.popitem()}") # 随机删除一个元素,无法指定
dic.popitem(): ('b', 2)
5.键keys()、值values()、键值对items()
# dic之键keys()、值values()、键值对items(),python2中取出的是列表(鸡蛋);python3中取出的是元组(鸡)
dic = {'a': 1, 'b': 2}
print(f"dic.keys(): {dic.keys()}")
print(f"dic.values(): {dic.values()}")
print(f"dic.items(): {dic.items()}")
dic.keys(): dict_keys(['a', 'b'])
dic.values(): dict_values([1, 2])
dic.items(): dict_items([('a', 1), ('b', 2)])
6.循环
# dic之循环
# dic是无序的,但是python3采用了底层优化算法,所以看起来是有序的,但是python2中的字典是无序
dic = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
for k, v in dic.items(): # items可以换成keys()、values()
print(k, v)
a 1
b 2
c 3
d 4
需要掌握(****)
- get
- update
- fromkeys
- setdefault
1.get()
# dic之get()
dic = {'a': 1, 'b': 2}
print(f"dic.get('a'): {dic.get('a')}")
print(f"dic.get('c'): {dic.get('c')}")
dic.get('a'): 1
dic.get('c'): None
2.update()
# dic之update()
dic1 = {'a': 1, 'b': 2}
dic2 = {'c': 3}
dic1.update(dic2)
print(f"dic1: {dic1}")
dic1: {'a': 1, 'b': 2, 'c': 3}
3.fromkeys()
# dic之fromkeys()
dic = dict.fromkeys(['name', 'age', 'sex'], None)
print(f"dic: {dic}")
dic: {'name': None, 'age': None, 'sex': None}
4.setdefault()
# dic之setdefault(),有指定key不会改变值;无指定key则改变值
dic = {'a': 1, 'b': 2}
print(f"dic.setdefault('a'): {dic.setdefault('a',3)}")
print(f"dic: {dic}")
print(f"dic.setdefault('c'): {dic.setdefault('c',3)}")
print(f"dic: {dic}")
dic.setdefault('a'): 1
dic: {'a': 1, 'b': 2}
dic.setdefault('c'): 3
dic: {'a': 1, 'b': 2, 'c': 3}