从以下字典object中,输出最小值和所对应的学号(字典是在result.txt文件中)
{'C0A21801': 58, 'C0A21802': 61, 'C0A21803': 71, 'C0B21901': 63, 'C0B21902': 88, 'C0B21903': 77}
file = "./data/result.txt"
with open(file, mode='r') as fileobj:
最低得分为58分、学号为C0A21801。
rawDict = {'C0A21801': 58, 'C0A21802': 61, 'C0A21803': 71, 'C0B21901': 63, 'C0B21902': 88, 'C0B21903': 77}
#获取最小值
minValue = min(rawDict.values())
#获取最小值对应的键
minKey = [k for k, v in a.items() if v == 58][0]
file = "./data/result.txt"
f = open(file,'w')
f.write("最低得分为{}分、学号为{}。".format(minValue, minKey)+'\n')
f.close()
import json
# ./data/result.txt这种写法,python文件必须与data在同一个目录中,否则会报错;或者使用绝对路径
with open("./data/result.txt", 'r', encoding='utf-8') as f:
# 处理单引号为双引用,否则json.loads(result)会报错
result = f.read().replace("'", '"')
data = json.loads(result)
try:
if type(data is dict):
new_data = sorted(data.items(), key=lambda item: item[0]) # 按照value进行排序;
# 最低得分为58分、学号为C0A21801。
print("最低得分为:{}分、学号为:{}".format(new_data[0][1], new_data[0][0]))
except Exception as e:
print(e)