数据容器--字典dit
定义以及相关操作
my_dict = {"林俊杰":{
"语文":99,"数学":98,"英语":85
},"周杰伦":{
"语文":94,"数学":92,"英语":95
},"李笠":{
"语文":100,"数学":99,"英语":97
}}
score = my_dict["周杰伦"]["语文"]
print(f"周杰伦的语文成绩是{score}")
字典的常用操作:
my_dict = {"周杰伦":99}
#添加操作
my_dict["李笠"] = 999
#更新操作
my_dict["李笠"] = 98
#删除元素pop
score = my_dict.pop("李笠")
#清空元素clear
my_dict.clear()
print(my_dict)
"""
#获取全部keys
my_dict = {"周杰伦":98,"林觉姐":95,"张学友":99,"李笠":100}
keys = my_dict.keys()
#方式一,通过获取全部的key来遍历字典
# for key in keys:
# print(f"字典的key是:{key}")
# print(f"字典的value是:{my_dict[key]}")
#方式二,直接对字典进行for循环,每一次循环直接得到key
for key in my_dict:
print(f"字典的key是:{key}")
print(f"字典的value是:{my_dict[key]}")
#统计数量
number = len((my_dict))
print(f"字典的元素数量有{number}个")
#练习
my_dict = {"王力宏":{
"部门":"科研部","工资":3000,"级别":1
},"周杰伦":{
"部门":"市场部","工资":5000,"级别":2
},"林俊杰":{
"部门":"市场部","工资":7000,"级别":3
},"张学友":{
"部门":"科研部","工资":4000,"级别":1
},"刘德华":{
"部门":"市场部","工资":6000,"级别":2
}}
keys = my_dict.keys()
for key in keys:
jibie = my_dict[key]["级别"]
if jibie == 1:
jibie = jibie + 1
bounce = my_dict[key]["工资"]+1000
my_dict[key]["级别"]=jibie
my_dict[key]["工资"]=bounce
print(my_dict)
排序的结果成为列表对象
mylist = [1,6,3,8,4,5,2]
#元组
myturple = (7,2,1,9,4,5,6)
#字符串
mystr = "dhasiudha"
#集合
myset = {5,1,3,9,4,5,8}
#字典
mydict = {"key3":3,"key5":1,"key1":2,"key4":7,"key2":5}
#排序,加上逗号reverse=True表示反向排序
print(f"列表对象的排序结果是:{sorted(mylist,reverse=True)}")
print(f"元组对象的排序结果是:{sorted(myturple,reverse=True)}")
print(f"字符串对象的排序结果是:{sorted(mystr,reverse=True)}")
print(f"集合对象的排序结果是:{sorted(myset,reverse=True)}")
print(f"字典对象的排序结果是:{sorted(mydict,reverse=True)}")
#字符串是按位比较,也就是一位一位进行比较
#通过Ascll比较
print(f"abd>abc结果是:{'abd'>'abc'}")
print(f"ab>a结果是:{'ab'>'a'}")
print(f"a>A结果是:{'a'>'A'}")
print(f"a<A结果是:{'a'<'A'}")#False