python 字典所有操作

Posted ericblog1992

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 字典所有操作相关的知识,希望对你有一定的参考价值。

# 字典的创建
# 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(‘编号不存在‘)

以上是关于python 字典所有操作的主要内容,如果未能解决你的问题,请参考以下文章

python进阶学习chapter02(列表字典集合操作)

python-字典操作

python字典操作

python字典的操作

python字典操作函数

python字典操作方法详解