Python对字典进行排序、查找最大最小值

2022-05-03 00:00:00 排序 字典 最小值

这段代码对字典按照value进行排序,求最大、最小值

"""
皮蛋编程(https://www.pidancode.com)
创建日期:2022/4/27
功能描述:Python对字典进行排序、查找最大最小值
"""

prices = {
   'Pidancode': 32.23,
   'Freepythoncode': 345.78,
   'Baidu': 3385.55,
   'Google': 47.20,
   'Bandao': 10.75
}

# Find min and max price
min_price = min(zip(prices.values(), prices.keys()))
max_price = max(zip(prices.values(), prices.keys()))

print('min price:', min_price)
print('max price:', max_price)

print('sorted prices:')
prices_sorted = sorted(zip(prices.values(), prices.keys()))
for price, name in prices_sorted:
    print('    ', name, price)

输出:

min price: (10.75, 'Bandao')
max price: (3385.55, 'Baidu')
sorted prices:
     Bandao 10.75
     Pidancode 32.23
     Google 47.2
     Freepythoncode 345.78
     Baidu 3385.55

代码在Python3.9下测试通过

相关文章