python第八课
字典
info = {"k1":"v1", "k2":"v2"}
字典里面保存了两个值,每一个都是键值对。
info = {"k1": 18, "k2": True, 1:"asdf",
"k3": [11, 22, 33, {"kk1": "vv1", "kk2": "vv2", "kk3": (11, 22)}], "k4": (11, 22, 33)}
字典的value可以是任意值,列表不能作为字典的key,元组可以,布尔值可以作为字典的key,但作为key时会和1、0冲突,字典也不能作为字典的key,会报错nohashable。
info = {0: "11", True: "234", (1, 2): "star",} print(info) {0: '11', True: '234', (1, 2): 'star'} info = {1: "11", True: "234", (1, 2): "star",} print(info) {1: '234', (1, 2): 'star'}
python3.6以前的字典是无序的,以后的都是改写了算法,是有序的了。
字典的索引,用dict["key"]
info = {"k1": 18, 2: True, "k3": [11, 22, 33, {"kk1": "vv1", "kk2": "vv2", "kk3": (11, 22)}], "k4": (11, 22, 33)} print(info["k3"][3]["kk3"][0])
删除操作
del dict["key"]
for 循环
默认循环所有的key
info = {"k1": 18, 2: True, "k3": [11, 22, 33, {"kk1": "vv1", "kk2": "vv2", "kk3": (11, 22)}], "k4": (11, 22, 33)} for item in info.keys(): print(item) for k, v in info.items(): print(k, v)
方法
clear
copy
fromkeys
循环可迭代对象创建给予的key生成字典
v = dict.fromkeys(["k1","k2","k3"],123)
->{'k1': 123, 'k2': 123, 'k3': 123}
get
x = v.get('k1', 121) print(x)
pop
x = v.pop('k1') print(v)
x = v.pop('k', 90)
print(v, x)
popitem
x = v.popitem() print(v)
默认删除最后一个,因为3.6以后字典有序
setdefult
x = v.setdefault('k1', '122') print(v, x) -》{'k1': 123, 'k2': 123} 123
x = v.setdefault('k3', '122')
print(v, x)
-》{'k1': 123, 'k2': 123, 'k3': '122'} 122
如果不存在设置的值,则增加一项键值对。
update
v.update(k1=120, k2=121,k4=233) print(v) -》{'k1': 120, 'k2': 121, 'k3': '122', 'k4': 233}
常用:keys() values() items() get() update()