python-3.x - python字典获取键
问题描述
我看到有几个人说
for key, value in dict.items():
print(key)
是一种比其他方式更 Pythonic 的方式。为什么人们不使用 keys() 功能?
for key in dict.keys():
print(key)
解决方案
因为如果您只需要键,那么作为可迭代对象的 dict 对象将已经生成键:
for key in dictionary:
print(key)
如果您需要字典的值,则使用以下items
方法:
for key, value in dictionary.items():
print(key, value)
使代码比使用键访问 dict 值更具可读性:
for key in dictionary:
print(key, dict[key])
该keys
方法的唯一实际用途是进行set
基于 - 的操作,因为该keys
方法返回一个类似集合的视图:
# use set intersection to obtain common keys between dict1 and dict2
for key in dict1.keys() & dict2.keys():
print(key)
推荐阅读
- google-bigquery - BigQuery 作业并发政策更改错误
- php - Laravel HasMany 不返回任何结果 - 甚至不查询?
- java - 关联 Java 字段类型和泛型参数
- javascript - 无法使用来自 TypeScript npm 包的多个导入
- r - 我想添加数据框的递增连续列
- python - 在 Google Cloud Platform 中启动 python gmailAPI 脚本时的身份验证问题
- android - 如何在 Android Studio 中使用改造从数据库中搜索用户?解决了
- windows - Windows 10 的 React Native 最新版本问题
- c++ - 逐字获取字符串的函数
- javascript - 长输入的更快解决方案?