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()用法及代碼示例
- Python Dictionary fromkeys()用法及代碼示例
- Python Dictionary clear()用法及代碼示例
- Python Dictionary update()用法及代碼示例
- Python Dictionary pop()用法及代碼示例
- Python Dictionary setdefault()用法及代碼示例
- Python Dictionary popitem()用法及代碼示例
- Python Dictionary has_key()用法及代碼示例
- Python Dictionary get()用法及代碼示例
- Python Dictionary items()用法及代碼示例
- Python Dictionary copy()用法及代碼示例
- Python Dictionary values()用法及代碼示例
- Python Decimal shift()用法及代碼示例
- Python Decimal next_plus()用法及代碼示例
- Python Decimal logical_and()用法及代碼示例
- Python Decimal rotate()用法及代碼示例
- Python Decimal max_mag()用法及代碼示例
- Python Datetime.replace()用法及代碼示例
- Python Decimal as_integer_ratio()用法及代碼示例
- Python DataFrame.to_excel()用法及代碼示例
注:本文由純淨天空篩選整理自 Python Dictionary keys() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。