python字典基础知识

#字典 key不允许出现重复,value可以出现重复
#使用大括号{}创建
dict1 = {}
dict2 = {"name":"李","age":"23"}
#利用函数dict创建字典
dict3 =dict(name="李畅",sex="男")
print(dict3)
#dict.formkeys创建键值
dict4 = dict.fromkeys(['name','sex','hiredate','grade'])
print(dict4)

#字典的取值
employee  = dict(name='王峰',sex='男',hiredate='1997-10-20',grade='A'
                 ,job='销售',salry='1000')
print(employee)
print(employee['name'])

job = employee.get('job')
print(job)
print(employee.get('dept','其他部门'))

#判断key是否在字典中
print('name' in employee)
#遍历字典
for  key in employee:#把key以此取出来
    v=employee[key]
    print(key,end="")
    print(v)

for key,value in employee.items():
    print(key,value)
#字典的更新操作
employee['name'] = '李畅'
print(employee)
#多个key直进行更新
employee.update(salry = 12000,job='信息')
print(employee)

#删除指定kv
employee.pop('salry')
print(employee)
#删除末端kv
employee.popitem()
print(employee)

#清空字典
employee.clear()
print(employee)

#为字典设置默认值
emp1 = {'name':'jacky','grade':'B'}
emp2 = {'name':'lily',}
emp2.setdefault('grade','C')#如果不存在则设置,如果存在则不管

# if 'grade' not in emp2:
#     emp2['grade'] = 'C'
print(emp2)

#获取字典的视图
#获取所有的键
ks=employee.keys()
print(ks)
vs = employee.values()
print(vs)
its = employee.items()  #修改视图后字典也会变化
print(its)

#用字典字符串的格式化
emp_str = "姓名:%(name)s,评级:%(grade)s"%emp1#其中name是键,
print(emp_str)
#新版本字典格式化
emp_str = "姓名:{name},评级:{grade}".format_map(emp1)
print(emp_str)

#字典的散列值hash

新闻标题:python字典基础知识
文章起源:http://azwzsj.com/article/jcseeh.html