无涯教程-Python3 - dict.keys()函数

180 阅读1分钟

Python keys()方法用于从字典中获取所有键。它返回键列表,如果字典为空,则返回一个空列表。此方法不带任何参数。该方法的语法如下。

dict.keys - 语法

keys()

dict.keys - 返回

它返回键列表。如果字典为空,则为None。

首先让无涯教程看一个简单的示例,从字典中获取键。

# Python dictionary keys() Method
# 创建字典
product = {name:laptop,brand:hp,price:80000}
# 调用方法
p = product.keys()
print(p)

输出

dict_keys([name, brand, price])
dict.keys - Python字典keys()方法示例2
# 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

参考链接

www.learnfk.com/python3/pyt…