2.17 字典创建 person = {"name": "alex", 'age': 20} person = dict(name='seven', age=20) -------------------------------- keys = {1,2,3,4,5} print({}.fromkeys(keys)) {1: None, 2: None, 3: None, 4: None, 5: None} ---------------------------------- keys = {1,2,3,4,5} print({}.fromkeys(keys,100)) {1: 100, 2: 100, 3: 100, 4: 100, 5: 100} ------------------- 字典创建操作 1. dic.keys() 返回字典包含的所有key 列表 persion = {"name":"alex","age":20} print(persion.keys()) dict_keys(['name', 'age']) 2. dic.values() 返回字典包含的所有values persion = {"name":"alex","age":20} print(persion.values()) dict_values(['alex', 20]) 3. dic.items() 返回字典包含的所有key和values persion = {"name":"alex","age":20} print(persion.items()) dict_items([('name', 'alex'), ('age', 20)]) ------------------- 增1 persion = {"name":"alex","age":20} 如果字典的key不存在,则直接新增 如果字典的key存在,则会替换新赋值的 value persion['sex'] = 'boy' {'name': 'alex', 'age': 20, 'sex': 'boy'} ------------------------------- 增2 setdefault(k,v) persion.setdefault('eat','猪肉') 如果字典的key不存在,则直接由 dict[key] = default {'name': 'alex', 'age': 20, 'eat': '猪肉'} ------------------- persion.setdefault('name','大傻瓜') 如果字典的key 存在, 那么直接返回之前的value,这种操作比较安全 {'name': 'alex', 'age': 20} 删1 pop() persion.pop("name") 如果字典中存在key,删除并返回key对应的vuale: alex 如果key不存在,且没有给出default的值,则引发keyerror异常; persion = {"name":"alex","age":20} print(persion.pop("name1",-1)) name1 不存在,又指定了,返回-1 ,如果不存在,则返回-1 删2 popitem() 随机返回并删除字典中的一对键和值,如果字典已经为空,却调用了此方法,就报出KeyError异常 persion = {"name":"alex","age":20,"sex":"女","喜欢":"吃肉"} print(persion.popitem()) 删3 clear() 清空字典 修改 update() persion = {"name":"alex","age":20} persion2 = {"name":"alex","age":30} persion.update(persion2) 仔细看,age变成了30. update()里面跟的谁, 如果重复的value,就以()里面的value为主导 print(persion) {'name': 'alex', 'age': 30} 查看1 persion('name') alex ,如果key不存在,报错 查看2 get() persion.get(key, default = None) 返回字典中key对应的值,若key不存在字典中, 则返回default的值(default默认为None) persion = {"name":"alex","age":20,"sex":"女","喜欢":"吃肉",'1':'2'} persion.get(key,default='不存在') print(persion.get("美女",'不存在')) D:Pythonpython.exe E:/pycode/test.py 不存在 循环1 for k in persion.keys() 循环2 for k in persion.values() 循环3 for k in persion: print(k,persion[k]) 循环4 for k,v in persion.items(): print(k,v) 长度 len() persion = {"name":"alex","age":20,"sex":"女","喜欢":"吃肉",'1':'2'} print(len(persion)) 返回长度 5