字典
练习题:
1、字典基本操作
字典内容如下:
dic = {
'python': 95,
'java': 99,
'c': 100
}
用程序解答下面的题目:
字典的长度是多少
请修改’java’ 这个key对应的value值为98
删除 c 这个key
增加一个key-value对,key值为 php, value是90
获取所有的key值,存储在列表里
获取所有的value值,存储在列表里
判断 javascript 是否在字典中
获得字典里所有value 的和
获取字典里最大的value
获取字典里最小的value
字典 dic1 = {‘php’: 97}, 将dic1的数据更新到dic中
答案:
dic = {
'python': 95,
'java': 99,
'c': 100
}
print(len(dic))
3
###################################################################
dic2 = {'java': 98}
dic.update(dic2)
print(dic)
{'python': 95, 'java': 98, 'c': 100}
###################################################################
print(dic.pop(c), dic) # 是字符的话,需要加引号
Traceback (most recent call last):
File "D:\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 2910, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-8-0ebb7b4c6f8f>", line 1, in <module>
print(dic.pop(c), dic)
NameError: name 'c' is not defined
print(dic.pop("c"), dic)
100 {'python': 95, 'java': 98}
###################################################################
dic3 = {'php':90}
dic.update(dic3)
print(dic)
{'python': 95, 'java': 98, 'php': 90}
###################################################################
key_lst = list(dic.keys())
print(key_lst)
['python', 'java', 'php']
###################################################################
val_lst = list(dic.values())
print(val_list)
Traceback (most recent call last):
File "D:\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 2910, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-16-b0c31bf205dc>", line 1, in <module>
print(val_list)
NameError: name 'val_list' is not defined
print(val_lst)
[95, 98, 90]
###################################################################
if ' javascript' in dic:
print("键 javascript 存在")
else:
print("键 javascript 不存在")
键 javascript 不存在
num = 0
###################################################################
for value in dic.values():
print(value)
num += int(value)
print(num)
95
98
90
283
###################################################################
print(max(val_lst))
98
###################################################################
print(min(val_lst))
90
###################################################################
dic1 = {'php': 97}
dic.update(dic1)
print(dic.update()) # dic更新的操作,不能直接打印
None
print(dic) # 只能打印更新后的字典dic
{'python': 95, 'java': 98, 'php': 97}
2、字典中的value
有一个字典,保存的是学生各个编程语言的成绩,内容如下
data = {
‘python’: {‘上学期’: ‘90’, ‘下学期’: ‘95’},
‘c++’: [‘95’, ‘96’, ‘97’],
‘java’: [{‘月考’:‘90’, ‘期中考试’: ‘94’, ‘期末考试’: ‘98’}]
}
各门课程的考试成绩存储方式并不相同,有的用字典,有的用列表,但是分数都是字符串类型,请实现函数transfer_score(score_dict),将分数修改成int类型.
# 觉得要用上这个循环,还不知道该如何处理嵌套中的字典
for i in data:
if type(data[i]) is dict:
print(data[i])
print(type(data[i]))
dic2 = data[i]
print(dic2.keys())
#dic3 = int(dic2.values())
#print(dic3)
#dic2.update()
#print(dic2)
#print(type(dic2.values()))
else:
print(data[i])
print("##")