Python3 中的 dict.keys()函数

首页 / Python3入门教程 / Python3 中的 dict.keys()函数

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

dict.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

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

React实战进阶45讲 -〔王沛〕

程序员进阶攻略 -〔胡峰〕

白话法律42讲 -〔周甲徳〕

研发效率破局之道 -〔葛俊〕

设计模式之美 -〔王争〕

RPC实战与核心原理 -〔何小锋〕

Kafka核心源码解读 -〔胡夕〕

徐昊 · TDD项目实战70讲 -〔徐昊〕

零基础GPT应用入门课 -〔林健(键盘)〕

好记忆不如烂笔头。留下您的足迹吧 :)