"""
字典应用
字典中保存了股票信息,完成下面的操作
1.找出股票价格大于100元的股票并创建一个新的字典
2、找出价格最高和最低的股票对应的股票代码
3.按照股票价格从高到低给股票代码排序
"""
stocks = {
'AAPL': 191.88,
'G00G': 1186.96,
'IBM': 149.24,
'ORCL': 48.44,
'ACN': 166.89,
'FB': 208.09,
'SYMC': 21.29
}
# 方法一:找出股票价格大于100元的股票并创建一个新的字典
new_stocks = {}
for key, value in stocks.items():
if value > 100:
new_stocks[key] = value
print(new_stocks)
# 方法二,找出股票价格大于100元的股票并创建一个新的字典
new_stocks = {key: value for key, value in stocks.items() if value > 100}
print(new_stocks)
# zip函数的使用
dict1 = dict(zip('ABCDE', [1, 2, 3, 4]))
print(dict1) # {'A': 1, 'B': 2, 'C': 3, 'D': 4}
# 方法一,找出价格最高和最低的股票对应的股票代码
print(max(zip(stocks.values(), stocks.keys())))
print(max(zip(stocks.values(), stocks.keys()))[1])
print(min(zip(stocks.values(), stocks.keys()))[1])
# 方法二,找出价格最高和最低的股票对应的股票代码
_, max_code = max(zip(stocks.values(), stocks.keys()))
print(max_code)
# 排序
words = ['apple', 'zoo', 'watermelon', 'zealot', 'internationalization', 'pear']
print(max(words)) # 自然排序
print(max(words, key=len)) # 按字符串长度排序
words.sort(key=len)
print(words)
# 方法三,找出价格最高和最低的股票对应的股票代码
print(max(stocks, key=stocks.get))
print(min(stocks, key=stocks.get))
# 按照股票价格从高到低给股票代码排序
print(sorted(stocks, key=stocks.get, reverse=True))