Python keys()方法用于从字典中获取所有键。它返回键列表,如果字典为空,则返回一个空列表。此方法不带任何参数。该方法的语法如下。
keys()
它返回键列表。如果字典为空,则为None。
首先让无涯教程看一个简单的示例,从字典中获取键。
# Python dictionary keys() Method # 创建字典 product = {'name':'laptop','brand':'hp','price':80000} # 调用方法 p = product.keys() print(p)
输出:
dict_keys(['name', 'brand', 'price'])
# Python dictionary keys() Method # 创建字典 product = {'name':'laptop','brand':'hp','price':80000} # 使用键和值迭代 for p in product.keys(): if p == 'price' and product[p] > 50000: print("product price is too high",)
输出:
product price is too high
无涯教程可以在python程序中使用这种方法。在这里,将其用于程序中以检查库存状态。
# Python dictionary keys() Method # Creating a dictionary inventory = {'apples': 25, 'bananas': 220, 'oranges': 525, 'pears': 217} # Calling method for akey in inventory.keys(): if akey == 'bananas' and inventory[akey] > 200: print("We have sufficient inventory for the ", akey)
输出:
We have sufficient inventory for the bananas
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)