dic = {'a': 1, 'b': 2}
print(dic)
# 增: 字典名[key] = 值 => key已存在就是修改值,不存在就是新增值
dic['c'] = 3
print(dic)
# 改
dic['c'] = 30
print(dic)
# 查:字典名[key]
print(dic['c']) # 只能查找已有的key,没有崩溃
# 有默认值的查询:有key取出对应value,没有返还默认值,默认值可以自定义
print(dic.get('d', 'http://www.baidu.com'))
# 删
print(dic)
# 清空
# pop(k)删除指定key的value并返还删除的value
res = dic.pop('a')
# 从dic末尾删除,返还(key, value)形成的元组
res = dic.popitem()
print(dic, res)
# 其他方法
# 更新: a有值覆盖,c没被新操作,带下来,b为新增,增加并赋值
dic = {'a': 1, 'c': 2}
d = {'a': 10, 'b': 20}
dic.update(d)
print(dic) # {'a': 10, 'c': 2, 'b': 20}
# 带默认值的新增: 新增key,key已有,啥事不干,没有添加key,值就是第二个参数
dic.setdefault('z', 100)
print(dic)
# 字典的循环
# 1.直接循环,就是循环得到key
for k in dic:
print(k)
# 2.循环keys
print(dic.keys()) for k in dic.keys(): print(k)
# 3.循环values
print(dic.values())
for v in dic.values():
print(v)
# 同时循环key和value (key, value)
print(dic.items())
a, b = (1, 2)
print(a, b)
for res in dic.items():
print(res)
# 重点
for k, v in dic.items():
print(k, v)
# 解压赋值
a, _, _, b = (1, 2, 3, 4)