python-3.x - 以下字典 python 3.8 中的最大值及其键
问题描述
输入是:book_shop = {'sci fi': 12, 'mystery': 15, 'horror': 8, 'mythology': 10, 'young_adult': 4, 'adventure':14}
输出必须是:The highest selling book genre is mystery and the number of books sold are 15
需要在不使用 max 函数的情况下解决这个问题。
我试过这个:
book_shop = {'sci fi': 12, 'mystery': 15, 'horror': 8, 'mythology': 10, 'young_adult': 4, 'adventure':14}
largest = 0
for key, value in book_shop.items():
if largest in book_shop.values():
largest = book_shop.values()
key = book_shop.keys()
print("The highest selling book genre is ", key, " and the number of books sold are ", largest)
输出来了:The highest selling book genre is adventure and the number of books sold are 0
该怎么办?
解决方案
您可以使用以下方法获取具有最大值的密钥:
max_key = max(book_shop,key=book_shop.get)
print("The highest selling book genre is ", max_key, " and the no of books sold are ",book_shop.get(max_key))
更新了您的代码以在没有 max 函数的情况下获得最大值。基本上,您应该将最大值与该特定键的值进行比较。
In [193]: book_shop = {'sci fi': 12, 'mystery': 15, 'horror': 8, 'mythology': 10, 'young_adult': 4, 'adventure':14}
...: largest = 0
...: key1= ""
...: for key, value in book_shop.items():
...: #print("key ",key," value ",value)
...: if largest < int(book_shop.get(key)):
...: #print(True)
...: largest = value
...: key1 = key
...:
...: print("The highest selling book genre is ", key1, " and the number of books sold are ", largest)
推荐阅读
- ios - 使用颤振编译到iOS时找不到错误是什么
- python - r2 score turns out to be negative
- c# - 使用 Parallel ForEach 在 API 中发布并单个处理每个响应
- python - 从多个 json 文件为 matplotlib 创建 python 字典
- amazon-web-services - 如何使用脚本在 terraform 中使用 aws_instance 调用二进制对象?
- google-apps-script - 显示 web 应用程序正在运行的 code.gs 文件
- spring-boot - spring-data-elasticsearch 搜索模板
- c++ - Node.js 在 C/C++ 中添加模块
- authentication - Google AI Predict API:网站匿名身份验证
- c++ - 使用函数 bool.getCharacter(char* c) 读取标准输入并打印标准输出