info = { 'stu1101': "TengLan Wu", 'stu1102': "LongZe Luola", 'stu1103': "XiaoZe Maliya", }
字典的特性:
dict是无序的
key必须是唯一的,so 天生去重
增加
info["stu1104"] = "苍井空"
修改
info['stu1101'] = "武藤兰"
删除
info.pop("stu1101") #标准删除姿势
del info['stu1103'] #换个姿势删除
{'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya'} #随机删除
>>> info.popitem()
查找
>>> info = {'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya'} >>> >>> "stu1102" in info #标准用法 True >>> info.get("stu1102") #获取 'LongZe Luola' >>> info["stu1102"] #同上,但是看下面 'LongZe Luola' >>> info["stu1105"] #如果一个key不存在,就报错,get不会,不存在只返回None Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'stu1105'
#values >>> info.values() dict_values(['LongZe Luola', 'XiaoZe Maliya']) #keys >>> info.keys() dict_keys(['stu1102', 'stu1103']) #setdefault >>> info.setdefault("stu1106","Alex") 'Alex' >>> info {'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya', 'stu1106': 'Alex'} >>> info.setdefault("stu1102","龙泽萝拉") 'LongZe Luola' >>> info {'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya', 'stu1106': 'Alex'} #update >>> info {'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya', 'stu1106': 'Alex'} >>> b = {1:2,3:4, "stu1102":"龙泽萝拉"} >>> info.update(b) >>> info {'stu1102': '龙泽萝拉', 1: 2, 3: 4, 'stu1103': 'XiaoZe Maliya', 'stu1106': 'Alex'} #items info.items() dict_items([('stu1102', '龙泽萝拉'), (1, 2), (3, 4), ('stu1103', 'XiaoZe Maliya'), ('stu1106', 'Alex')])
#通过一个列表生成默认dict,有个没办法解释的坑,少用吧这个 >>> dict.fromkeys([1,2,3],'testd') {1: 'testd', 2: 'testd', 3: 'testd'}
循环dict
#方法1 for key in info: print(key,info[key]) #方法2 for k,v in info.items(): #会先把dict转成list,数据里大时莫用 print(k,v)