my_dict = {"name": "周杰伦", "age": 12, "sex": "女"}
my_dict1 = {}
my_dict2 = dict()
print(type(my_dict), my_dict) # {'name': '周杰伦', 'age': 12, 'sex': '女'}
print(type(my_dict1)) #
print(type(my_dict2)) #
# 字典不能使用下标索引,但是可以通过key值海取得对应的value
语法:字典[key] 可以取到对应的value
例子:
my_dict = {"name": "周杰伦", "age": 12, "sex": "女"}
name = my_dict["name"]
print(name) # 周杰伦
# 字典嵌套
字典的key和value可以是任意数据类型(key不可以为字典)---表明可以嵌套
# 从嵌套字典中获取数据
语法:字典[key][key]
例子:
stu_score_dict = {
"小明": {
"语文": 90,
"数学": 98,
"英语": 80
},
"小红": {
"语文": 91,
"数学": 92,
"英语": 83
},
"小天": {
"语文": 94,
"数学": 95,
"英语": 86
},
}
score = stu_score_dict["小红"]["语文"]
print(score)
# 新增元素
语法:字典[key] = value ----字典被修改,新增了元素
例子:
test_dict = {"name": "周杰伦", "age": 12, "sex": "女"}
test_dict["爱好"] = "唱歌"
print(test_dict) # {'name': '周杰伦', 'age': 12, 'sex': '女', '爱好': '唱歌'}
# 更新元素
语法:字典[key] = value ---- 字典被修改,元素被更新
例子:
test_dict = {"name": "周杰伦", "age": 12, "sex": "女"}
test_dict["name"] = "张杰"
print(test_dict) # {'name': '张杰', 'age': 12, 'sex': '女'}
# 删除元素
语法:字典.pop(key) ---获得指定的key和value,同时字典被修改,指定key的数据被删除
例子:
test_dict = {"name": "周杰伦", "age": 12, "sex": "女"}
value = test_dict.pop("name")
print(value) # 周杰伦
print(test_dict) # {'age': 12, 'sex': '女'}
# 清空字典
语法:字典.clear() --- 字典被修改,元素被清空
例子:
test_dict = {"name": "周杰伦", "age": 12, "sex": "女"}
test_dict.clear()
print(test_dict) # {}
# 获取全部的key
语法:字典.keys()
例子:
test_dict = {"name": "周杰伦", "age": 12, "sex": "女"}
test_keys = test_dict.keys()
print(test_keys) # dict_keys(['name', 'age', 'sex'])
for可以,while不可以(不支持下标索引)
test_dict = {"name": "周杰伦", "age": 12, "sex": "女"}
test_keys = test_dict.keys()
# 方式1:通过获取到全部的key完成遍历
for key in test_keys:
print(key)
print(test_dict[key])
# 方式2:直接对字典进行for循环,每一次循环都是直接得到key
for key in test_dict:
print(key)
print(test_dict[key])
# 统计字典内的数量
语法:len(字典)
例子:
test_dict = {"name": "周杰伦", "age": 12, "sex": "女"}
print(len(test_dict)) # 3
小案例:级别为1时,则级别加1,工资加1000
money_list = []
grade_list = []
worker_list = {
"1": {
"部门": "科技部",
"工资": 3000,
"级别": 1
},
"2": {
"部门": "市场部",
"工资": 5000,
"级别": 2
},
"3": {
"部门": "市场部",
"工资": 7000,
"级别": 3
},
"4": {
"部门": "科技部",
"工资": 4000,
"级别": 1
},
"5": {
"部门": "市场部",
"工资": 6000,
"级别": 2
}
}
for key in worker_list:
# print(key)
# print(worker_list[key]["级别"])
if worker_list[key]["级别"] == 1:
worker_list[key]["级别"] += 1
worker_list[key]["工资"] += 1000
# print(worker_list[key]["级别"])
# print(worker_list[key]["工资"])
money_list.append((worker_list[key]["工资"])) # 这里不能集合,因为集合的元素不重复,工资和级别会重复
grade_list.append((worker_list[key]["级别"]))
print(money_list) # [4000, 5000, 7000, 5000, 6000]
print(grade_list) # [2, 2, 3, 2, 2]