Python全栈之路:字典dict常用方法

特性:

  • dict无序
  • key唯一,天生去重

常用函数

dict.clear() 删除字典中所有元素
dict.copy() 返回字典(浅复制)的一个副本
dict.get(key,default=None) 对字典dict中的键key,返回它对应的值value,如果字典中不存在此键,则返回default 的值(注意,参数default 的默认值为None)
dict.has_key(key) 如果键(key)在字典中存在,返回True,否则返回False
dict.items() 返回一个包含字典中(键, 值)对元组的列表
dict.keys() 返回一个包含字典中键的列表
dict.values() 返回一个包含字典中所有值的列表
dict.pop(key[, default]) 和方法get()相似,如果字典中key 键存在,删除并返回dict[key],如果key 键不存在,且没有给出default 的值,引发KeyError 异常。

参考:Python中dict字典使用方法

创建字典

way 1:(小心列表坑!)

d = dict.fromkeys([1, 2, 3], ["name", "age"])
print("d:", d)
# ->d: {1: ['name', 'age'], 2: ['name', 'age'], 3: ['name', 'age']}

d[1][0] = "company"  # 浅拷贝
print("d of modify:", d)  # 此处,列表中的信息都被修改了
# ->d of modify: {1: ['company', 'age'], 2: ['company', 'age'], 3: ['company', 'age']}

way 2:

info = {
    "teacher1": "苍井空",
    "teacher2": "小泽玛利亚",
    "teacher3": "泷泽萝拉"
}

字典无序输出

print("info", info)
# ->info {'teacher2': '小泽玛利亚', 'teacher3': '泷泽萝拉', 'teacher1': '苍井空'}

查询

print(info["teacher1"])  # 不存在则报错
# ->苍井空
print(info.get("teacher5"))  # 推荐方式,不会报错
# ->None
print("teacher1" in info)  # py2:info.has_key("teacher5")
# ->True
print("keys:", info.keys())
# ->keys: dict_keys(['teacher2', 'teacher1', 'teacher3'])
print("values:", info.values())
# ->values: dict_values(['小泽玛利亚', '苍井空', '泷泽萝拉'])
print("items:", info.items())
# ->items: dict_items([('teacher2', '小泽玛利亚'),
# ('teacher1', '苍井空'), ('teacher3', '泷泽萝拉')])

修改

info["teacher1"] = "天海翼"  # 存在会被修改
print("modify:", info)
# ->modify: {'teacher2': '小泽玛利亚', 'teacher1': '天海翼', 'teacher3': '泷泽萝拉'}

增加

info["teacher4"] = "上原瑞穗"  # 没有则会创建
info.setdefault("teacher1", "樱井莉亚")  # 存在则不会被修改
print("add:", info)
# ->add: {'teacher4': '上原瑞穗', 'teacher2': '小泽玛利亚',
# 'teacher3': '泷泽萝拉', 'teacher1': '天海翼'}

b = {
    "teacher1": "樱井莉亚",
    "teacher5": "桃谷绘里香"
}
info.update(b)
print("update:", info)
# ->update: {'teacher1': '樱井莉亚', 'teacher4': '上原瑞穗',
#  'teacher2': '小泽玛利亚', 'teacher3': '泷泽萝拉', 'teacher5': '桃谷绘里香'}

删除

del info["teacher1"]
info.pop("teacher2")  # 标准写法
info.popitem()  # 随机删除一个
print("delete:", info)
# ->delete: {'teacher5': '桃谷绘里香', 'teacher3': '泷泽萝拉'}

遍历

for i in info:  # 推荐
print(i, info[i])
# teacher5 桃谷绘里香
# teacher3 泷泽萝拉

print("*"*50)
for key, value in info.items():  # 先转列表,在遍历,如果字典过大,会变慢
print(key, value)
# teacher5 桃谷绘里香
# teacher3 泷泽萝拉

清空

info.clear()
print("clear:", info)
# ->clear: {}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值