欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

python 字典所有操作

程序员文章站 2022-08-03 18:46:54
# 字典的创建# dict1 = {}# print(type(dict1))## dict2 = {# 'name':'汪峰',# 'sex':'男',# 'hiredate':'1997-10-20'# }# print(dict2)## dict3 = dict(name = 'eric',a ......
# 字典的创建
# dict1 = {}
# print(type(dict1))
#
# dict2 = {
# 'name':'汪峰',
# 'sex':'男',
# 'hiredate':'1997-10-20'
# }
# print(dict2)
#
# dict3 = dict(name = 'eric',age = 28)
# print(dict3)

# 取值操作
# employee = {
# 'name':'汪峰',
# 'sex':'男',
# 'grade':'a',
# 'hiredate':'1997-10-20',
# 'salary': 1000,
# 'welfare':100
# }
# name = employee['name']
# print(name)
#
# sex = employee.get('sex')
# print(sex)
#
# dept = employee.get('dept','其他部门')
# print(dept)

# in 成员运算符 判断 key 是否存在
# print('name' in employee) # true
# print('dept' in employee) # false
# print('dept' not in employee) # true

# 遍历字典
# 汪峰
# 男
# 1997-10-20
# for key in employee:
# v = employee[key]
# print(v)

# name 汪峰
# sex 男
# hiredate 1997-10-20
# for k,v in employee.items():
# print(k,v)


# 单个更新
# employee['grade'] = 'b'
# print(employee)
# # 多个更新
# employee.update(salary = 1200, welfare = 150)
# print(employee)
#
# # 新增
# employee['dept'] = '研发部'
# print(employee)
#
# # 删除操作
# employee.pop('dept')
# print(employee)
# # 删除操作 删除最后一个 kv
# employee.popitem()
# print(employee)
#
# # 清空字典
# employee.clear()
# print(employee)


# emp1 = {'name':'jacky','grade':'b','hiredate':'1989-10-12'}
# emp2 = {'name':'lily','grade':'a','hiredate':'1989-10-12'}
#
# # setdefault 设置默认值 存在就忽略 不存在就创建
# emp2.setdefault('grade','c')
# print(emp2)

# 获取字典的视图
# k = emp1.keys()
# # dict_keys(['name', 'grade'])
# print(k)
#
# v = emp1.values()
# # dict_values(['jacky', 'b'])
# print(v)
#
# items = emp1.items()
# # dict_items([('name', 'jacky'), ('grade', 'b')])
# print(items)

# 格式化字符串
# emp_str = "姓名:{name},评级:{grade},入职时间{hiredate}".format_map(emp1)
# print(emp_str)

# 散列值
# h1 = hash("dabc")
# # print(h1)
# # h2 = hash("1231231")
# # print(h2)

# 例子
source = "12345,jace,ercd,php,5000$2345,clead,ercd,dfd,5000$22345,clead,ercd,dfd,5000$32345,clead,ercd,dfd,5000"
employee_list = source.split("$")
print(employee_list)

all_emp = {}
for i in range(0,len(employee_list)):
# print(i)
e = employee_list[i].split(",")
# print(e)
employee = {'no':e[0],'name':e[1],'www':e[2],'jod':e[3],'salary':e[4]}
print(employee)
all_emp[employee['no']] = employee
print(all_emp)

empno = input('编号:')
if empno in all_emp:
emp = all_emp.get(empno)
print(emp);
else:
print('编号不存在')