當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python Dictionary keys()用法及代碼示例

Python keys() 方法用於從字典中獲取所有鍵。如果字典為空,它返回一個鍵列表和一個空列表。該方法不帶任何參數。該方法的語法如下。

簽名

keys()

參數

沒有參數

返回

它返回一個鍵列表。如果字典為空,則無。

讓我們看一些 keys() 方法的例子來了解它的函數。

Python字典keys()方法示例1

讓我們首先看一個從字典中獲取鍵的簡單示例。

# Python dictionary keys() Method
# Creating a dictionary
product = {'name':'laptop','brand':'hp','price':80000}
# Calling method
p = product.keys()
print(p)

輸出:

dict_keys(['name', 'brand', 'price'])

Python字典keys()方法示例2

# Python dictionary keys() Method
# Creating a dictionary
product = {'name':'laptop','brand':'hp','price':80000}
# Iterating using key and value
for p in product.keys():
    if p == 'price' and product[p] > 50000:
        print("product price is too high",)

輸出:

product price is too high

Python字典keys()方法示例3

我們可以在我們的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






相關用法


注:本文由純淨天空篩選整理自 Python Dictionary keys() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。